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
ccd14e450fcefa5b286c06221775f50a49059f6d
2024-04-04 12:40:31
Riccardo Busetti
fix(metrics_layer): Fix the failure rate calculation (#68160)
false
Fix the failure rate calculation (#68160)
fix
diff --git a/src/sentry/snuba/metrics/fields/base.py b/src/sentry/snuba/metrics/fields/base.py index d2dc6d95b9ea47..145a55ccaf63c9 100644 --- a/src/sentry/snuba/metrics/fields/base.py +++ b/src/sentry/snuba/metrics/fields/base.py @@ -23,6 +23,7 @@ abnormal_sessions, abnormal_users, addition, + all_duration_transactions, all_sessions, all_spans, all_transactions, @@ -1607,6 +1608,14 @@ def generate_where_statements( project_ids=project_ids, org_id=org_id, metric_ids=metric_ids, alias=alias ), ), + SingularEntityDerivedMetric( + metric_mri=TransactionMRI.ALL_DURATION.value, + metrics=[TransactionMRI.DURATION.value], + unit="transactions", + snql=lambda project_ids, org_id, metric_ids, alias=None: all_duration_transactions( + metric_ids=metric_ids, alias=alias + ), + ), SingularEntityDerivedMetric( metric_mri=TransactionMRI.FAILURE_COUNT.value, metrics=[TransactionMRI.DURATION.value], @@ -1619,7 +1628,7 @@ def generate_where_statements( metric_mri=TransactionMRI.FAILURE_RATE.value, metrics=[ TransactionMRI.FAILURE_COUNT.value, - TransactionMRI.ALL.value, + TransactionMRI.ALL_DURATION.value, ], unit="transactions", snql=lambda failure_count, tx_count, project_ids, org_id, metric_ids, alias=None: division_float( @@ -1638,7 +1647,7 @@ def generate_where_statements( metric_mri=TransactionMRI.HTTP_ERROR_RATE.value, metrics=[ TransactionMRI.HTTP_ERROR_COUNT.value, - TransactionMRI.ALL.value, + TransactionMRI.ALL_DURATION.value, ], unit="transactions", snql=lambda http_error_count, tx_count, project_ids, org_id, metric_ids, alias=None: division_float( diff --git a/src/sentry/snuba/metrics/fields/snql.py b/src/sentry/snuba/metrics/fields/snql.py index a0c570c82384bd..c73af996b7a1ac 100644 --- a/src/sentry/snuba/metrics/fields/snql.py +++ b/src/sentry/snuba/metrics/fields/snql.py @@ -476,7 +476,7 @@ def _satisfaction_equivalence(org_id: int, satisfaction_tag_value: str) -> Funct ) -def _metric_id_equivalence(metric_condition: Function) -> Function: +def _metric_id_equivalence(metric_condition: Function | int) -> Function: return Function( "equals", [ @@ -560,6 +560,18 @@ def all_transactions( ) +def all_duration_transactions( + metric_ids: Sequence[int], + alias: str | None = None, +) -> Function: + return _count_if_with_conditions( + [ + _metric_id_equivalence(list(metric_ids)[0]), + ], + alias, + ) + + def apdex(satisfactory_snql, tolerable_snql, total_snql, alias: str | None = None) -> Function: return division_float( arg1_snql=addition(satisfactory_snql, division_float(tolerable_snql, 2)), diff --git a/src/sentry/snuba/metrics/naming_layer/mri.py b/src/sentry/snuba/metrics/naming_layer/mri.py index a99c1e87ba3320..5d91600a21099d 100644 --- a/src/sentry/snuba/metrics/naming_layer/mri.py +++ b/src/sentry/snuba/metrics/naming_layer/mri.py @@ -151,6 +151,7 @@ class TransactionMRI(Enum): # Derived ALL = "e:transactions/all@none" + ALL_DURATION = "e:transactions/all_duration@none" FAILURE_COUNT = "e:transactions/failure_count@none" FAILURE_RATE = "e:transactions/failure_rate@ratio" SATISFIED = "e:transactions/satisfied@none"
859ec911c97af4f6595c708c81ae7abe0221c357
2024-06-07 02:52:29
anthony sottile
ref: fix typing of bind_nodes (#72275)
false
fix typing of bind_nodes (#72275)
ref
diff --git a/src/sentry/eventstore/base.py b/src/sentry/eventstore/base.py index 6ec89b7b32d08d..8b57ea7fc1c05b 100644 --- a/src/sentry/eventstore/base.py +++ b/src/sentry/eventstore/base.py @@ -3,25 +3,18 @@ from collections.abc import Sequence from copy import deepcopy from datetime import datetime -from typing import Protocol import sentry_sdk from snuba_sdk import Condition from sentry import nodestore -from sentry.db.models.fields.node import NodeData from sentry.eventstore.models import Event +from sentry.models.rawevent import RawEvent from sentry.snuba.dataset import Dataset from sentry.snuba.events import Columns from sentry.utils.services import Service -class HasNodeData(Protocol): - @property - def data(self) -> NodeData: - ... - - class Filter: """ A set of conditions, start/end times and project, group and event ID sets @@ -269,7 +262,7 @@ def create_event(self, project_id=None, event_id=None, group_id=None, data=None) """ return Event(project_id=project_id, event_id=event_id, group_id=group_id, data=data) - def bind_nodes(self, object_list: Sequence[HasNodeData]) -> None: + def bind_nodes(self, object_list: Sequence[RawEvent | Event]) -> None: """ For a list of Event objects, and a property name where we might find an (unfetched) NodeData on those objects, fetch all the data blobs for
74a9f68b5b8a83b6eb7622b409d75414091cc22f
2019-03-02 03:20:16
Markus Unterwaditzer
fix: Dont create invalid level when creating a sample event (#12259)
false
Dont create invalid level when creating a sample event (#12259)
fix
diff --git a/src/sentry/api/endpoints/project_create_sample.py b/src/sentry/api/endpoints/project_create_sample.py index 0c5b212f55ef30..825fb79b71aa89 100644 --- a/src/sentry/api/endpoints/project_create_sample.py +++ b/src/sentry/api/endpoints/project_create_sample.py @@ -12,7 +12,7 @@ class ProjectCreateSampleEndpoint(ProjectEndpoint): def post(self, request, project): event = create_sample_event( - project, platform=project.platform, default='javascript', level=0 + project, platform=project.platform, default='javascript', ) data = serialize(event, request.user)
172f968b2aabbf9345f7f965ce10c3d51a8fb758
2023-06-06 03:15:14
Neel Shah
fix(sdk): Patch DSC public_key in relay_transport envelope (#50292)
false
Patch DSC public_key in relay_transport envelope (#50292)
fix
diff --git a/src/sentry/utils/sdk.py b/src/sentry/utils/sdk.py index f46dc5583c2127..284fdddb4d7521 100644 --- a/src/sentry/utils/sdk.py +++ b/src/sentry/utils/sdk.py @@ -395,6 +395,12 @@ def _capture_anything(self, method_name, *args, **kwargs): args_list = list(args) envelope = args_list[0] relay_envelope = copy.copy(envelope) + + # fix DSC public_key since SDK assumes everything is upstream_dsn + dsc = relay_envelope.headers.get("trace") + if dsc and relay_transport.parsed_dsn: + dsc["public_key"] = relay_transport.parsed_dsn.public_key + relay_envelope.items = envelope.items.copy() args = [relay_envelope, *args_list[1:]]
1b05cfc22193d0a83fe56d439f8b83f1ce7116ff
2024-08-16 03:11:29
Andrew Liu
feat(feedback): searchbar: fetch tags from issue platform and implement filterKeySections (#76242)
false
searchbar: fetch tags from issue platform and implement filterKeySections (#76242)
feat
diff --git a/static/app/components/feedback/feedbackSearch.tsx b/static/app/components/feedback/feedbackSearch.tsx index 92d053e07931fe..fa9f0498ed0f68 100644 --- a/static/app/components/feedback/feedbackSearch.tsx +++ b/static/app/components/feedback/feedbackSearch.tsx @@ -1,12 +1,15 @@ import type {CSSProperties} from 'react'; import {useCallback, useMemo} from 'react'; import styled from '@emotion/styled'; +import {orderBy} from 'lodash'; -import {fetchTagValues} from 'sentry/actionCreators/tags'; +import {fetchTagValues, useFetchOrganizationTags} from 'sentry/actionCreators/tags'; import {SearchQueryBuilder} from 'sentry/components/searchQueryBuilder'; +import type {FilterKeySection} from 'sentry/components/searchQueryBuilder/types'; import SmartSearchBar from 'sentry/components/smartSearchBar'; import {t} from 'sentry/locale'; import type {Tag, TagCollection, TagValue} from 'sentry/types/group'; +import type {Organization} from 'sentry/types/organization'; import {getUtcDateString} from 'sentry/utils/dates'; import {isAggregateField} from 'sentry/utils/discover/fields'; import { @@ -22,9 +25,9 @@ import {useLocation} from 'sentry/utils/useLocation'; import {useNavigate} from 'sentry/utils/useNavigate'; import useOrganization from 'sentry/utils/useOrganization'; import usePageFilters from 'sentry/utils/usePageFilters'; -import useTags from 'sentry/utils/useTags'; +import {Dataset} from 'sentry/views/alerts/rules/metric/types'; -const EXCLUDED_TAGS = [ +const EXCLUDED_TAGS: string[] = [ FeedbackFieldKey.BROWSER_VERSION, FeedbackFieldKey.EMAIL, FeedbackFieldKey.LOCALE_LANG, @@ -32,6 +35,11 @@ const EXCLUDED_TAGS = [ FeedbackFieldKey.NAME, FieldKey.PLATFORM, FeedbackFieldKey.OS_VERSION, + // These are found in issue platform and redundant (= __.name, ex os.name) + 'browser', + 'device', + 'os', + 'user', ]; const getFeedbackFieldDefinition = (key: string) => getFieldDefinition(key, 'feedback'); @@ -52,18 +60,20 @@ function fieldDefinitionsToTagCollection(fieldKeys: string[]): TagCollection { const FEEDBACK_FIELDS_AS_TAGS = fieldDefinitionsToTagCollection(FEEDBACK_FIELDS); /** - * Merges a list of supported tags and feedback search fields into one collection. + * Merges a list of supported tags and feedback search properties into one collection. */ -function getFeedbackSearchTags(supportedTags: TagCollection) { +function getFeedbackFilterKeys(supportedTags: TagCollection) { const allTags = { ...Object.fromEntries( - Object.keys(supportedTags).map(key => [ - key, - { - ...supportedTags[key], - kind: getFeedbackFieldDefinition(key)?.kind ?? FieldKind.TAG, - }, - ]) + Object.keys(supportedTags) + .filter(key => !EXCLUDED_TAGS.includes(key)) + .map(key => [ + key, + { + ...supportedTags[key], + kind: getFeedbackFieldDefinition(key)?.kind ?? FieldKind.TAG, + }, + ]) ), ...FEEDBACK_FIELDS_AS_TAGS, }; @@ -76,6 +86,41 @@ function getFeedbackSearchTags(supportedTags: TagCollection) { return Object.fromEntries(keys.map(key => [key, allTags[key]])); } +const getFilterKeySections = ( + tags: TagCollection, + organization: Organization +): FilterKeySection[] => { + if (!organization.features.includes('search-query-builder-user-feedback')) { + return []; + } + + const customTags: Tag[] = Object.values(tags).filter( + tag => + tag.kind === FieldKind.TAG && + !EXCLUDED_TAGS.includes(tag.key) && + !FEEDBACK_FIELDS.map(String).includes(tag.key) + ); + + const orderedTagKeys: string[] = orderBy( + customTags, + ['totalValues', 'key'], + ['desc', 'asc'] + ).map(tag => tag.key); + + return [ + { + value: 'feedback_field', + label: t('Suggested'), + children: Object.keys(FEEDBACK_FIELDS_AS_TAGS), + }, + { + value: FieldKind.TAG, + label: t('Tags'), + children: orderedTagKeys, + }, + ]; +}; + interface Props { className?: string; style?: CSSProperties; @@ -84,15 +129,47 @@ interface Props { export default function FeedbackSearch({className, style}: Props) { const {selection: pageFilters} = usePageFilters(); const projectIds = pageFilters.projects; - const {pathname, query} = useLocation(); + const {pathname, query: locationQuery} = useLocation(); const organization = useOrganization(); - const organizationTags = useTags(); const api = useApi(); - const feedbackTags = useMemo( - () => getFeedbackSearchTags(organizationTags), - [organizationTags] + const start = pageFilters.datetime.start + ? getUtcDateString(pageFilters.datetime.start) + : undefined; + const end = pageFilters.datetime.end + ? getUtcDateString(pageFilters.datetime.end) + : undefined; + const statsPeriod = pageFilters.datetime.period; + const tagQuery = useFetchOrganizationTags( + { + orgSlug: organization.slug, + projectIds: projectIds.map(String), + dataset: Dataset.ISSUE_PLATFORM, + useCache: true, + enabled: true, + keepPreviousData: false, + start: start, + end: end, + statsPeriod: statsPeriod, + }, + {} ); + const issuePlatformTags: TagCollection = useMemo(() => { + return (tagQuery.data ?? []).reduce<TagCollection>((acc, tag) => { + acc[tag.key] = {...tag, kind: FieldKind.TAG}; + return acc; + }, {}); + }, [tagQuery]); + // tagQuery.isLoading and tagQuery.isError are not used + + const filterKeys = useMemo( + () => getFeedbackFilterKeys(issuePlatformTags), + [issuePlatformTags] + ); + + const filterKeySections = useMemo(() => { + return getFilterKeySections(issuePlatformTags, organization); + }, [issuePlatformTags, organization]); const getTagValues = useCallback( (tag: Tag, searchQuery: string): Promise<string[]> => { @@ -103,13 +180,9 @@ export default function FeedbackSearch({className, style}: Props) { } const endpointParams = { - start: pageFilters.datetime.start - ? getUtcDateString(pageFilters.datetime.start) - : undefined, - end: pageFilters.datetime.end - ? getUtcDateString(pageFilters.datetime.end) - : undefined, - statsPeriod: pageFilters.datetime.period, + start: start, + end: end, + statsPeriod: statsPeriod, }; return fetchTagValues({ @@ -126,14 +199,7 @@ export default function FeedbackSearch({className, style}: Props) { } ); }, - [ - api, - organization.slug, - projectIds, - pageFilters.datetime.start, - pageFilters.datetime.end, - pageFilters.datetime.period, - ] + [api, organization.slug, projectIds, start, end, statsPeriod] ); const navigate = useNavigate(); @@ -143,20 +209,21 @@ export default function FeedbackSearch({className, style}: Props) { navigate({ pathname, query: { - ...query, + ...locationQuery, cursor: undefined, query: searchQuery.trim(), }, }); }, - [navigate, pathname, query] + [navigate, pathname, locationQuery] ); if (organization.features.includes('search-query-builder-user-feedback')) { return ( <SearchQueryBuilder - initialQuery={decodeScalar(query.query, '')} - filterKeys={feedbackTags} + initialQuery={decodeScalar(locationQuery.query, '')} + filterKeys={filterKeys} + filterKeySections={filterKeySections} getTagValues={getTagValues} onSearch={onSearch} searchSource={'feedback-list'} @@ -173,12 +240,12 @@ export default function FeedbackSearch({className, style}: Props) { placeholder={t('Search Feedback')} organization={organization} onGetTagValues={getTagValues} - supportedTags={feedbackTags} + supportedTags={filterKeys} excludedTags={EXCLUDED_TAGS} fieldDefinitionGetter={getFeedbackFieldDefinition} maxMenuHeight={500} defaultQuery="" - query={decodeScalar(query.query, '')} + query={decodeScalar(locationQuery.query, '')} onSearch={onSearch} /> </SearchContainer>
0482921c06abfb737594f165ef980bbbb843ff04
2022-08-10 04:01:15
Evan Purkhiser
style(ci): Shorten 'Component: Developer Environment' label (#37639)
false
Shorten 'Component: Developer Environment' label (#37639)
style
diff --git a/.github/labels.yml b/.github/labels.yml index 669971ea3523f7..82a1918498b263 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -101,7 +101,7 @@ description: '' - name: 'Component: Developer Environment' color: '584774' - description: This covers issues related to setting up a developer's environment to be able to contribute to Sentr + description: This covers issues related to setting up a developer's environment - name: 'Component: Documentation' color: '584774' description: ''
e864b655477e7cf82527aabac9ffb771cac3ba57
2022-06-16 04:52:59
Jenn Mueng
feat(search): Replace hotkeys labels with icons in search quick actions menu on mobile (#35693)
false
Replace hotkeys labels with icons in search quick actions menu on mobile (#35693)
feat
diff --git a/static/app/components/smartSearchBar/searchDropdown.tsx b/static/app/components/smartSearchBar/searchDropdown.tsx index 2d4abc73b82c11..66c3e0f76ace0e 100644 --- a/static/app/components/smartSearchBar/searchDropdown.tsx +++ b/static/app/components/smartSearchBar/searchDropdown.tsx @@ -120,6 +120,7 @@ class SearchDropdown extends PureComponent<Props> { <HotkeyGlyphWrapper> <HotkeysLabel value={action.hotkeys?.display ?? []} /> </HotkeyGlyphWrapper> + <IconWrapper>{action.icon}</IconWrapper> <HotkeyTitle>{action.text}</HotkeyTitle> </ActionButtonContainer> ); @@ -258,6 +259,7 @@ const DropdownFooter = styled(`div`)` justify-content: space-between; padding: ${space(1)}; flex-wrap: wrap; + gap: ${space(1)}; `; const ActionsRow = styled('div')` @@ -284,6 +286,21 @@ const ActionButtonContainer = styled('div')` const HotkeyGlyphWrapper = styled('span')` color: ${p => p.theme.gray300}; margin-right: ${space(0.5)}; + + @media (max-width: ${p => p.theme.breakpoints.small}) { + display: none; + } +`; + +const IconWrapper = styled('span')` + display: none; + + @media (max-width: ${p => p.theme.breakpoints.small}) { + display: flex; + margin-right: ${space(0.5)}; + align-items: center; + justify-content: center; + } `; const HotkeyTitle = styled(`span`)` diff --git a/static/app/components/smartSearchBar/types.tsx b/static/app/components/smartSearchBar/types.tsx index d49ed22c79ab02..e56c14d229b2e9 100644 --- a/static/app/components/smartSearchBar/types.tsx +++ b/static/app/components/smartSearchBar/types.tsx @@ -51,6 +51,7 @@ export enum QuickActionType { export type QuickAction = { actionType: QuickActionType; + icon: React.ReactNode; text: string; canRunAction?: ( token: TokenResult<any> | null | undefined, diff --git a/static/app/components/smartSearchBar/utils.tsx b/static/app/components/smartSearchBar/utils.tsx index 10a42e17ee3e83..4b3897e5d1aca5 100644 --- a/static/app/components/smartSearchBar/utils.tsx +++ b/static/app/components/smartSearchBar/utils.tsx @@ -5,7 +5,16 @@ import { Token, TokenResult, } from 'sentry/components/searchSyntax/parser'; -import {IconClock, IconStar, IconTag, IconToggle, IconUser} from 'sentry/icons'; +import { + IconArrow, + IconClock, + IconDelete, + IconExclamation, + IconStar, + IconTag, + IconToggle, + IconUser, +} from 'sentry/icons'; import {t} from 'sentry/locale'; import HotkeysLabel from '../hotkeysLabel'; @@ -260,6 +269,7 @@ export const quickActions: QuickAction[] = [ actual: 'option+backspace', display: 'option+backspace', }, + icon: <IconDelete size="xs" color="gray300" />, canRunAction: tok => { return tok?.type === Token.Filter; }, @@ -271,6 +281,7 @@ export const quickActions: QuickAction[] = [ actual: ['option+1', 'cmd+1'], display: 'option+!', }, + icon: <IconExclamation size="xs" color="gray300" />, canRunAction: tok => { return tok?.type === Token.Filter; }, @@ -282,6 +293,7 @@ export const quickActions: QuickAction[] = [ actual: ['option+left'], display: 'option+left', }, + icon: <IconArrow direction="left" size="xs" color="gray300" />, canRunAction: (tok, count) => { return count > 1 || (count > 0 && tok?.type !== Token.Filter); }, @@ -293,6 +305,7 @@ export const quickActions: QuickAction[] = [ actual: ['option+right'], display: 'option+right', }, + icon: <IconArrow direction="right" size="xs" color="gray300" />, canRunAction: (tok, count) => { return count > 1 || (count > 0 && tok?.type !== Token.Filter); },
faf76edf880491450b43aecd73d2f4416ab75108
2024-09-26 20:53:49
Evan Purkhiser
ref(rr6): Switch to a data memory router in tests (#78190)
false
Switch to a data memory router in tests (#78190)
ref
diff --git a/tests/js/sentry-test/reactTestingLibrary.tsx b/tests/js/sentry-test/reactTestingLibrary.tsx index b4d77dd2f541ac..479df3ae92a37c 100644 --- a/tests/js/sentry-test/reactTestingLibrary.tsx +++ b/tests/js/sentry-test/reactTestingLibrary.tsx @@ -1,10 +1,10 @@ import {Component} from 'react'; -import {Router} from 'react-router-dom'; +import {type RouteObject, RouterProvider, useRouteError} from 'react-router-dom'; import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla import {CacheProvider, ThemeProvider} from '@emotion/react'; +import {createMemoryHistory, createRouter} from '@remix-run/router'; import * as rtl from '@testing-library/react'; // eslint-disable-line no-restricted-imports import userEvent from '@testing-library/user-event'; // eslint-disable-line no-restricted-imports -import {createMemoryHistory} from 'history'; import * as qs from 'query-string'; import {makeTestQueryClient} from 'sentry-test/queryClient'; @@ -77,14 +77,20 @@ function makeAllTheProviders(providers: ProviderOptions) { // Inject legacy react-router 3 style router mocked navigation functions // into the memory history used in react router 6 + // + // TODO(epurkhiser): In a world without react-router 3 we should figure out + // how to write our tests in a simpler way without all these shims const history = createMemoryHistory(); + Object.defineProperty(history, 'location', {get: () => router.location}); history.replace = router.replace; history.push = (path: any) => { if (typeof path === 'object' && path.search) { path.query = qs.parse(path.search); delete path.search; delete path.hash; + delete path.state; + delete path.key; } // XXX(epurkhiser): This is a hack for react-router 3 to 6. react-router @@ -99,24 +105,36 @@ function makeAllTheProviders(providers: ProviderOptions) { router.push(path); }; - // TODO(__SENTRY_USING_REACT_ROUTER_SIX): For some reason getsentry is - // infering the type of this wrong. Unclear why that is happening - const Router6 = Router as any; + // By default react-router 6 catches exceptions and displays the stack + // trace. For tests we want them to bubble out + function ErrorBoundary(): React.ReactNode { + throw useRouteError(); + } - const routerContainer = window.__SENTRY_USING_REACT_ROUTER_SIX ? ( - <Router6 location={router.location} navigator={history}> - {content} - </Router6> - ) : ( - content - ); + const routes: RouteObject[] = [ + { + path: '*', + element: content, + errorElement: <ErrorBoundary />, + }, + ]; + + const memoryRouter = createRouter({ + future: {v7_prependBasename: true}, + history, + routes, + }).initialize(); return ( <LegacyRouterProvider> <CacheProvider value={{...cache, compat: true}}> <ThemeProvider theme={lightTheme}> <QueryClientProvider client={makeTestQueryClient()}> - {routerContainer} + {window.__SENTRY_USING_REACT_ROUTER_SIX ? ( + <RouterProvider router={memoryRouter} /> + ) : ( + content + )} </QueryClientProvider> </ThemeProvider> </CacheProvider>
755a304d7d5ebd1c9ea5a61e407d38924f4fcb65
2022-02-23 22:15:50
Joris Bayer
feat(metrics): Remove metrics extraction flags from flagr (#31995)
false
Remove metrics extraction flags from flagr (#31995)
feat
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index d156ef6f2f1650..c5905d198fc6c0 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -116,7 +116,7 @@ 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) -default_manager.add("organizations:metrics-extraction", OrganizationFeature, True) +default_manager.add("organizations:metrics-extraction", OrganizationFeature) default_manager.add("organizations:metrics-performance-ui", OrganizationFeature, True) default_manager.add("organizations:minute-resolution-sessions", OrganizationFeature) default_manager.add("organizations:mobile-screenshots", OrganizationFeature, True) @@ -156,7 +156,7 @@ default_manager.add("organizations:symbol-sources", OrganizationFeature) default_manager.add("organizations:team-insights", OrganizationFeature) default_manager.add("organizations:transaction-events", OrganizationFeature, True) -default_manager.add("organizations:transaction-metrics-extraction", 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)
3695da0a6b10f4eb17d5255d389aed48e8609abe
2024-02-01 00:00:51
Jonas
fix(compositeSelect): defer focus event to optimize INP (#64207)
false
defer focus event to optimize INP (#64207)
fix
diff --git a/static/app/components/compactSelect/composite.spec.tsx b/static/app/components/compactSelect/composite.spec.tsx index 71f0483573eee9..ec24bbef90c9df 100644 --- a/static/app/components/compactSelect/composite.spec.tsx +++ b/static/app/components/compactSelect/composite.spec.tsx @@ -123,12 +123,16 @@ describe('CompactSelect', function () { // press arrow up and second option in the first region gets focus await userEvent.keyboard('{ArrowUp}'); - expect(screen.getByRole('option', {name: 'Choice Two'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Choice Two'})).toHaveFocus(); + }); // press arrow down 3 times and focus moves to the third and fourth option, before // wrapping back to the first option await userEvent.keyboard('{ArrowDown>3}'); - expect(screen.getByRole('option', {name: 'Choice One'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Choice One'})).toHaveFocus(); + }); }); it('has separate, async self-contained select regions', async function () { diff --git a/static/app/components/compactSelect/control.tsx b/static/app/components/compactSelect/control.tsx index 881d03316d777d..5c237d3f50cfc7 100644 --- a/static/app/components/compactSelect/control.tsx +++ b/static/app/components/compactSelect/control.tsx @@ -33,6 +33,20 @@ import usePrevious from 'sentry/utils/usePrevious'; import type {SingleListProps} from './list'; import type {SelectOption} from './types'; +// autoFocus react attribute is sync called on render, this causes +// layout thrashing and is bad for performance. This thin wrapper function +// will defer the focus call until the next frame, after the browser and react +// have had a chance to update the DOM, splitting the perf cost across frames. +function nextFrameCallback(cb: () => void) { + if ('requestAnimationFrame' in window) { + window.requestAnimationFrame(() => cb()); + } else { + setTimeout(() => { + cb(); + }, 1); + } +} + export interface SelectContextValue { overlayIsOpen: boolean; /** @@ -311,45 +325,41 @@ export function Control({ shouldCloseOnBlur, preventOverflowOptions, flipOptions, - onOpenChange: async open => { - // On open - if (open) { - // Wait for overlay to appear/disappear - await new Promise(resolve => resolve(null)); - - // Focus on search box if present - if (searchable) { - searchRef.current?.focus(); - return; - } - - const firstSelectedOption = overlayRef.current?.querySelector<HTMLLIElement>( - `li[role="${grid ? 'row' : 'option'}"][aria-selected="true"]` - ); - - // Focus on first selected item - if (firstSelectedOption) { - firstSelectedOption.focus(); + onOpenChange: open => { + nextFrameCallback(() => { + if (open) { + // Focus on search box if present + if (searchable) { + searchRef.current?.focus(); + return; + } + + const firstSelectedOption = overlayRef.current?.querySelector<HTMLLIElement>( + `li[role="${grid ? 'row' : 'option'}"][aria-selected="true"]` + ); + + // Focus on first selected item + if (firstSelectedOption) { + firstSelectedOption.focus(); + return; + } + + // If no item is selected, focus on first item instead + overlayRef.current + ?.querySelector<HTMLLIElement>(`li[role="${grid ? 'row' : 'option'}"]`) + ?.focus(); return; } - // If no item is selected, focus on first item instead - overlayRef.current - ?.querySelector<HTMLLIElement>(`li[role="${grid ? 'row' : 'option'}"]`) - ?.focus(); - return; - } - - // On close - onClose?.(); + // On close + onClose?.(); - // Clear search string - setSearchInputValue(''); - setSearch(''); + // Clear search string + setSearchInputValue(''); + setSearch(''); - // Wait for overlay to appear/disappear - await new Promise(resolve => resolve(null)); - triggerRef.current?.focus(); + triggerRef.current?.focus(); + }); }, }); diff --git a/static/app/components/compactSelect/index.spec.tsx b/static/app/components/compactSelect/index.spec.tsx index 13b98536d98a05..5bc0392db2f44d 100644 --- a/static/app/components/compactSelect/index.spec.tsx +++ b/static/app/components/compactSelect/index.spec.tsx @@ -72,13 +72,22 @@ describe('CompactSelect', function () { await userEvent.click(screen.getByRole('button', {name: 'Option One'})); expect(screen.getByRole('option', {name: 'Option One'})).toBeInTheDocument(); await userEvent.click(document.body); - expect(screen.queryByRole('option', {name: 'Option One'})).not.toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByRole('option', {name: 'Option One'})).not.toBeInTheDocument(); + }); // Can be dismissed by pressing Escape await userEvent.click(screen.getByRole('button', {name: 'Option One'})); - expect(screen.getByRole('option', {name: 'Option One'})).toBeInTheDocument(); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Option One'})).toBeInTheDocument(); + }); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Option One'})).toHaveFocus(); + }); await userEvent.keyboard('{Escape}'); - expect(screen.queryByRole('option', {name: 'Option One'})).not.toBeInTheDocument(); + await waitFor(() => { + expect(screen.queryByRole('option', {name: 'Option One'})).not.toBeInTheDocument(); + }); // When menu A is open, clicking once on menu B's trigger button closes menu A and // then opens menu B @@ -230,11 +239,18 @@ describe('CompactSelect', function () { // there's a message prompting the user to use search to find more options expect(screen.getByText('Use search for more options…')).toBeInTheDocument(); + await waitFor(() => { + expect(screen.getByPlaceholderText('Search…')).toHaveFocus(); + }); // Option Three is not reachable via keyboard, focus wraps back to Option One await userEvent.keyboard(`{ArrowDown}`); - expect(screen.getByRole('option', {name: 'Option One'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Option One'})).toHaveFocus(); + }); await userEvent.keyboard(`{ArrowDown>2}`); - expect(screen.getByRole('option', {name: 'Option One'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('option', {name: 'Option One'})).toHaveFocus(); + }); // Option Three is still available via search await userEvent.type(screen.getByPlaceholderText('Search…'), 'three'); @@ -371,7 +387,9 @@ describe('CompactSelect', function () { // close the menu await userEvent.click(document.body); - expect(onCloseMock).toHaveBeenCalled(); + await waitFor(() => { + expect(onCloseMock).toHaveBeenCalled(); + }); }); }); @@ -520,6 +538,9 @@ describe('CompactSelect', function () { // there's a message prompting the user to use search to find more options expect(screen.getByText('Use search for more options…')).toBeInTheDocument(); + await waitFor(() => { + expect(screen.getByPlaceholderText('Search…')).toHaveFocus(); + }); // Option Three is not reachable via keyboard, focus wraps back to Option One await userEvent.keyboard(`{ArrowDown}`); expect(screen.getByRole('row', {name: 'Option One'})).toHaveFocus(); @@ -663,7 +684,9 @@ describe('CompactSelect', function () { // close the menu await userEvent.click(document.body); - expect(onCloseMock).toHaveBeenCalled(); + await waitFor(() => { + expect(onCloseMock).toHaveBeenCalled(); + }); }); it('allows keyboard navigation to nested buttons', async function () { diff --git a/static/app/components/organizations/hybridFilter.spec.tsx b/static/app/components/organizations/hybridFilter.spec.tsx index 532d63d760d165..68661ecab69f9a 100644 --- a/static/app/components/organizations/hybridFilter.spec.tsx +++ b/static/app/components/organizations/hybridFilter.spec.tsx @@ -1,4 +1,10 @@ -import {fireEvent, render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; +import { + fireEvent, + render, + screen, + userEvent, + waitFor, +} from 'sentry-test/reactTestingLibrary'; import {HybridFilter} from 'sentry/components/organizations/hybridFilter'; @@ -155,15 +161,21 @@ describe('ProjectPageFilter', function () { // Open the menu, focus is on search input await userEvent.click(screen.getByRole('button', {expanded: false})); - expect(screen.getByPlaceholderText('Search…')).toHaveFocus(); + await waitFor(() => { + expect(screen.getByPlaceholderText('Search…')).toHaveFocus(); + }); // Press Arrow Down to move focus to Option One await userEvent.keyboard('{ArrowDown}'); - expect(screen.getByRole('row', {name: 'Option One'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('row', {name: 'Option One'})).toHaveFocus(); + }); // Press Arrow Right to move focus to the checkbox await userEvent.keyboard('{ArrowRight}'); - expect(screen.getByRole('checkbox', {name: 'Select Option One'})).toHaveFocus(); + await waitFor(() => { + expect(screen.getByRole('checkbox', {name: 'Select Option One'})).toHaveFocus(); + }); // Activate the checkbox. In browsers, users can press Space when the checkbox is // focused to activate it. With RTL, however, onChange events aren't fired on Space diff --git a/static/app/views/dashboards/detail.spec.tsx b/static/app/views/dashboards/detail.spec.tsx index b3de7c421d59eb..fe31066c9ab1dc 100644 --- a/static/app/views/dashboards/detail.spec.tsx +++ b/static/app/views/dashboards/detail.spec.tsx @@ -1105,13 +1105,15 @@ describe('Dashboards > Detail', function () { screen.getByText('All Releases'); await userEvent.click(document.body); - expect(browserHistory.push).toHaveBeenCalledWith( - expect.objectContaining({ - query: expect.objectContaining({ - release: '', - }), - }) - ); + await waitFor(() => { + expect(browserHistory.push).toHaveBeenCalledWith( + expect.objectContaining({ + query: expect.objectContaining({ + release: '', + }), + }) + ); + }); }); it('can save absolute time range in existing dashboard', async () => {
8c07f13b1909fc3191d10f24c853c970815055cf
2024-11-27 18:04:48
Ryan Albrecht
ci(eslint): Remove a few lint rules that are later overridden in .eslintrc.js (#81111)
false
Remove a few lint rules that are later overridden in .eslintrc.js (#81111)
ci
diff --git a/.eslintrc.js b/.eslintrc.js index 8ef646861cd018..dfb3482ca6aa79 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,44 +12,15 @@ const baseRules = { /** * Variables */ - // https://eslint.org/docs/rules/no-shadow - 'no-shadow': ['error'], - // https://eslint.org/docs/rules/no-shadow-restricted-names 'no-shadow-restricted-names': ['error'], - // https://eslint.org/docs/rules/no-undef - 'no-undef': ['error'], - - // https://eslint.org/docs/rules/no-unused-vars - 'no-unused-vars': [ - 'error', - { - vars: 'all', - args: 'none', - - // Ignore vars that start with an underscore - // e.g. if you want to omit a property using object spread: - // - // const {name: _name, ...props} = this.props; - // - varsIgnorePattern: '^_', - argsIgnorePattern: '^_', - }, - ], - - // https://eslint.org/docs/rules/no-use-before-define - 'no-use-before-define': ['error', {functions: false}], - /** * Possible errors */ // https://eslint.org/docs/rules/no-cond-assign 'no-cond-assign': ['error', 'always'], - // https://eslint.org/docs/rules/no-console - 'no-console': ['warn'], - // https://eslint.org/docs/rules/no-alert 'no-alert': ['error'], @@ -272,14 +243,6 @@ const reactReactRules = { // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-deprecated.md 'react/no-deprecated': ['error'], - // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md - 'react/no-is-mounted': ['warn'], - - // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-find-dom-node.md - // Recommended to use callback refs instead - // TODO: Upgrade sentry to use callback refs - 'react/no-find-dom-node': ['warn'], - // Prevent usage of the return value of React.render // deprecation: https://facebook.github.io/react/docs/react-dom.html#render // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-render-return-value.md @@ -311,10 +274,6 @@ const reactReactRules = { // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-typos.md 'react/no-typos': ['error'], - // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-string-refs.md - // This is now considered legacy, callback refs preferred - 'react/no-string-refs': ['warn'], - // Prevent invalid characters from appearing in markup // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-unescaped-entities.md 'react/no-unescaped-entities': ['off'], @@ -416,16 +375,6 @@ const reactImportRules = { }, ], - // Enforce a convention in module import order - // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/order.md - 'import/order': [ - 'error', - { - groups: ['builtin', 'external', 'internal', ['parent', 'sibling', 'index']], - 'newlines-between': 'always', - }, - ], - // Require a newline after the last import/require in a group // https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/newline-after-import.md 'import/newline-after-import': ['error'], @@ -499,7 +448,6 @@ const reactImportRules = { }; const reactJestRules = { - 'jest/no-large-snapshots': ['warn', {maxSize: 2000}], 'jest/no-disabled-tests': 'error', }; @@ -540,22 +488,6 @@ const reactRules = { 'asc', {caseSensitive: true, natural: false, requiredFirst: true}, ], - - // Disallow importing `import React from 'react'`. This is not needed since - // React 17. We prefer the named imports for potential tree-shaking gains - // in the future. - 'no-restricted-imports': [ - 'error', - { - paths: [ - { - name: 'react', - importNames: ['default'], - message: 'Prefer named React imports (React types DO NOT need imported!)', - }, - ], - }, - ], }; const appRules = { @@ -572,6 +504,7 @@ const appRules = { // no-undef is redundant with typescript as tsc will complain // A downside is that we won't get eslint errors about it, but your editors should // support tsc errors so.... + // https://eslint.org/docs/rules/no-undef 'no-undef': 'off', // Let formatter handle this @@ -579,12 +512,14 @@ const appRules = { /** * Need to use typescript version of these rules + * https://eslint.org/docs/rules/no-shadow */ 'no-shadow': 'off', '@typescript-eslint/no-shadow': 'error', // This only override the `args` rule (which is "none"). There are too many errors and it's difficult to manually // fix them all, so we'll have to incrementally update. + // https://eslint.org/docs/rules/no-unused-vars 'no-unused-vars': 'off', '@typescript-eslint/no-unused-vars': [ 'error', @@ -606,6 +541,7 @@ const appRules = { }, ], + // https://eslint.org/docs/rules/no-use-before-define 'no-use-before-define': 'off', // This seems to have been turned on while previously it had been off '@typescript-eslint/no-use-before-define': ['off'], @@ -787,6 +723,7 @@ const appRules = { }; const strictRules = { + // https://eslint.org/docs/rules/no-console 'no-console': ['error'], // https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/no-is-mounted.md
81fe4639f45131021cb8d9f293389283cb96bee1
2021-02-26 22:50:45
Alex Xu @ Sentry
fix(ui): add comma to unsaved changes message (#24130)
false
add comma to unsaved changes message (#24130)
fix
diff --git a/src/sentry/static/sentry/app/views/dashboardsV2/detail.tsx b/src/sentry/static/sentry/app/views/dashboardsV2/detail.tsx index a847deeb61fee4..b5050856fad501 100644 --- a/src/sentry/static/sentry/app/views/dashboardsV2/detail.tsx +++ b/src/sentry/static/sentry/app/views/dashboardsV2/detail.tsx @@ -28,7 +28,7 @@ import DashboardTitle from './title'; import {DashboardDetails, DashboardState, Widget} from './types'; import {cloneDashboard} from './utils'; -const UNSAVED_MESSAGE = t('You have unsaved changes are you sure you want to leave?'); +const UNSAVED_MESSAGE = t('You have unsaved changes, are you sure you want to leave?'); type Props = { api: Client;
da458918a2297f2c4c0ea68d0d061e77374cc048
2021-11-04 23:51:15
Matej Minar
test: Fix pipeline assertion (#29790)
false
Fix pipeline assertion (#29790)
test
diff --git a/tests/js/spec/views/integrationPipeline/pipelineView.spec.jsx b/tests/js/spec/views/integrationPipeline/pipelineView.spec.jsx index b057deccf94d91..d1fe086904ef98 100644 --- a/tests/js/spec/views/integrationPipeline/pipelineView.spec.jsx +++ b/tests/js/spec/views/integrationPipeline/pipelineView.spec.jsx @@ -12,13 +12,13 @@ jest.mock( ); describe('PipelineView', () => { - it('renders awsLambdaProjectSelect', async () => { + it('renders awsLambdaProjectSelect', () => { mountWithTheme( <PipelineView pipelineName="awsLambdaProjectSelect" someField="someVal" />, {context: TestStubs.routerContext()} ); - await screen.findByText('mock_AwsLambdaProjectSelect'); + expect(screen.getByText('mock_AwsLambdaProjectSelect')).toBeInTheDocument(); expect(document.title).toBe('AWS Lambda Select Project'); });
982f363bfd97c8cfc410bb0c4a14e1605b145630
2023-02-23 18:08:40
Priscila Oliveira
feat(feature-flag): Add dynamic sampling feature flag for hide transaction name option - (#45033)
false
Add dynamic sampling feature flag for hide transaction name option - (#45033)
feat
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 66cfc47262681e..d185ccc9924c64 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1129,6 +1129,8 @@ def SOCIAL_AUTH_DEFAULT_USERNAME(): "organizations:dashboards-edit": True, # Enable metrics enhanced performance in dashboards "organizations:dashboards-mep": False, + # Enable the dynamic sampling "Transaction Name" priority in the UI + "organizations:dynamic-sampling-transaction-name-priority": False, # Enable minimap in the widget viewer modal in dashboards "organizations:widget-viewer-modal-minimap": False, # Enable experimental performance improvements. diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index 1d731824ff4e09..a90c2697cc17ac 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -196,6 +196,7 @@ default_manager.add("organizations:discover-basic", OrganizationFeature) default_manager.add("organizations:discover-query", OrganizationFeature) default_manager.add("organizations:dynamic-sampling", OrganizationFeature) +default_manager.add("organizations:dynamic-sampling-transaction-name-priority", OrganizationFeature, True) default_manager.add("organizations:event-attachments", OrganizationFeature) default_manager.add("organizations:global-views", OrganizationFeature) default_manager.add("organizations:incidents", OrganizationFeature)
1505e961aae108997814df20eefd44bc966a61f0
2023-10-13 02:07:22
Evan Purkhiser
ref(crons): Produce back-up clock pulses across all partitions (#57943)
false
Produce back-up clock pulses across all partitions (#57943)
ref
diff --git a/src/sentry/monitors/tasks.py b/src/sentry/monitors/tasks.py index bc149e778272a4..abd1e90bbaa2d7 100644 --- a/src/sentry/monitors/tasks.py +++ b/src/sentry/monitors/tasks.py @@ -1,10 +1,13 @@ import logging from datetime import datetime +from functools import lru_cache +from typing import Mapping import msgpack import sentry_sdk -from arroyo import Topic +from arroyo import Partition, Topic from arroyo.backends.kafka import KafkaPayload, KafkaProducer, build_kafka_configuration +from confluent_kafka.admin import AdminClient, PartitionMetadata from django.conf import settings from django.utils import timezone @@ -16,7 +19,11 @@ from sentry.tasks.base import instrumented_task from sentry.utils import metrics, redis from sentry.utils.arroyo_producer import SingletonProducer -from sentry.utils.kafka_config import get_kafka_producer_cluster_options, get_topic_definition +from sentry.utils.kafka_config import ( + get_kafka_admin_cluster_options, + get_kafka_producer_cluster_options, + get_topic_definition, +) from .models import CheckInStatus, MonitorCheckIn, MonitorEnvironment, MonitorStatus, MonitorType @@ -38,7 +45,7 @@ MONITOR_TASKS_LAST_TRIGGERED_KEY = "sentry.monitors.last_tasks_ts" -def _get_monitor_checkin_producer() -> KafkaProducer: +def _get_producer() -> KafkaProducer: cluster_name = get_topic_definition(settings.KAFKA_INGEST_MONITORS)["cluster"] producer_config = get_kafka_producer_cluster_options(cluster_name) producer_config.pop("compression.type", None) @@ -46,7 +53,21 @@ def _get_monitor_checkin_producer() -> KafkaProducer: return KafkaProducer(build_kafka_configuration(default_config=producer_config)) -_checkin_producer = SingletonProducer(_get_monitor_checkin_producer) +_checkin_producer = SingletonProducer(_get_producer) + + +@lru_cache(maxsize=None) +def _get_partitions() -> Mapping[int, PartitionMetadata]: + topic = settings.KAFKA_INGEST_MONITORS + cluster_name = get_topic_definition(topic)["cluster"] + + conf = get_kafka_admin_cluster_options(cluster_name) + admin_client = AdminClient(conf) + result = admin_client.list_topics(topic) + topic_metadata = result.topics.get(topic) + + assert topic_metadata + return topic_metadata.partitions def _dispatch_tasks(ts: datetime): @@ -130,9 +151,9 @@ def try_monitor_tasks_trigger(ts: datetime): @instrumented_task(name="sentry.monitors.tasks.clock_pulse", silo_mode=SiloMode.REGION) def clock_pulse(current_datetime=None): """ - This task is run once a minute when to produce a 'clock pulse' into the + This task is run once a minute when to produce 'clock pulses' into the monitor ingest topic. This is to ensure there is always a message in the - topic that can drive the clock which dispatches the monitor tasks. + topic that can drive all partition clocks, which dispatch monitor tasks. """ if current_datetime is None: current_datetime = timezone.now() @@ -146,9 +167,14 @@ def clock_pulse(current_datetime=None): "message_type": "clock_pulse", } - # Produce the pulse into the topic payload = KafkaPayload(None, msgpack.packb(message), []) - _checkin_producer.produce(Topic(settings.KAFKA_INGEST_MONITORS), payload) + + # We create a clock-pulse (heart-beat) for EACH available partition in the + # topic. This is a requirement to ensure that none of the partitions stall, + # since the global clock is tied to the slowest partition. + for partition in _get_partitions().values(): + dest = Partition(Topic(settings.KAFKA_INGEST_MONITORS), partition.id) + _checkin_producer.produce(dest, payload) @instrumented_task( diff --git a/tests/sentry/monitors/test_tasks.py b/tests/sentry/monitors/test_tasks.py index 1b122a9c2c7be8..aae7a989d907c5 100644 --- a/tests/sentry/monitors/test_tasks.py +++ b/tests/sentry/monitors/test_tasks.py @@ -1,9 +1,12 @@ from datetime import datetime, timedelta +from typing import MutableMapping from unittest import mock import msgpack import pytest +from arroyo import Partition, Topic from arroyo.backends.kafka import KafkaPayload +from confluent_kafka.admin import PartitionMetadata from django.test import override_settings from django.utils import timezone @@ -919,17 +922,27 @@ def test_timeout_with_future_complete_checkin(self, mark_checkin_timeout_mock): @override_settings(SENTRY_EVENTSTREAM="sentry.eventstream.kafka.KafkaEventStream") @mock.patch("sentry.monitors.tasks._checkin_producer") def test_clock_pulse(checkin_producer_mock): - clock_pulse() - - assert checkin_producer_mock.produce.call_count == 1 - assert checkin_producer_mock.produce.mock_calls[0] == mock.call( - mock.ANY, - KafkaPayload( - None, - msgpack.packb({"message_type": "clock_pulse"}), - [], - ), - ) + partition_count = 2 + + mock_partitions: MutableMapping[int, PartitionMetadata] = {} + for idx in range(partition_count): + mock_partitions[idx] = PartitionMetadata() + mock_partitions[idx].id = idx + + with mock.patch("sentry.monitors.tasks._get_partitions", lambda: mock_partitions): + clock_pulse() + + # One clock pulse per partition + assert checkin_producer_mock.produce.call_count == len(mock_partitions.items()) + for idx in range(partition_count): + assert checkin_producer_mock.produce.mock_calls[idx] == mock.call( + Partition(Topic("monitors-test-topic"), idx), + KafkaPayload( + None, + msgpack.packb({"message_type": "clock_pulse"}), + [], + ), + ) @mock.patch("sentry.monitors.tasks._dispatch_tasks")
83145a533dfe4b959d62dc42ee45b9121fda70f0
2025-01-24 23:42:52
anthony sottile
ref: fix types for sentry.integrations.notifications (#84009)
false
fix types for sentry.integrations.notifications (#84009)
ref
diff --git a/pyproject.toml b/pyproject.toml index 42c0dab109938f..16e44e9a96ea0a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -191,7 +191,6 @@ module = [ "sentry.integrations.msteams.client", "sentry.integrations.msteams.integration", "sentry.integrations.msteams.notifications", - "sentry.integrations.notifications", "sentry.integrations.pagerduty.actions.form", "sentry.integrations.pagerduty.client", "sentry.integrations.pagerduty.integration", diff --git a/src/sentry/integrations/notifications.py b/src/sentry/integrations/notifications.py index 7122dc6878f474..cf1d16b46f104b 100644 --- a/src/sentry/integrations/notifications.py +++ b/src/sentry/integrations/notifications.py @@ -47,10 +47,11 @@ def _get_channel_and_integration_by_user( # recipients. return {} - identity_id_to_idp = { - identity.id: identity_service.get_provider(provider_id=identity.idp_id) - for identity in identities - } + identity_id_to_idp = {} + for identity in identities: + idp = identity_service.get_provider(provider_id=identity.idp_id) + if idp is not None: + identity_id_to_idp[identity.id] = idp all_integrations = integration_service.get_integrations( organization_id=organization.id, @@ -76,7 +77,7 @@ def _get_channel_and_integration_by_user( def _get_channel_and_integration_by_team( team_id: int, organization: Organization, provider: ExternalProviders -) -> Mapping[str, RpcIntegration]: +) -> dict[str, RpcIntegration]: org_integrations = integration_service.get_organization_integrations( status=ObjectStatus.ACTIVE, organization_id=organization.id ) @@ -94,7 +95,7 @@ def _get_channel_and_integration_by_team( integration = integration_service.get_integration( integration_id=external_actor.integration_id, status=ObjectStatus.ACTIVE ) - if not integration: + if integration is None or external_actor.external_id is None: return {} return {external_actor.external_id: integration}
d6b3b45573ecc2318735df305a9d47c06208e47d
2021-06-09 18:47:34
Priscila Oliveira
ref(app-store-connect): Add new design changes (#26357)
false
Add new design changes (#26357)
ref
diff --git a/static/app/components/globalAppStoreConnectUpdateAlert/updateAlert.tsx b/static/app/components/globalAppStoreConnectUpdateAlert/updateAlert.tsx index b1253a52b526bf..8104b118df0b5a 100644 --- a/static/app/components/globalAppStoreConnectUpdateAlert/updateAlert.tsx +++ b/static/app/components/globalAppStoreConnectUpdateAlert/updateAlert.tsx @@ -15,7 +15,7 @@ import {AppStoreConnectValidationData} from 'app/types/debugFiles'; import {promptIsDismissed} from 'app/utils/promptIsDismissed'; import withApi from 'app/utils/withApi'; -import {getAppConnectStoreUpdateAlertMessage} from './utils'; +import {appStoreConnectAlertMessage, getAppConnectStoreUpdateAlertMessage} from './utils'; const APP_STORE_CONNECT_UPDATES = 'app_store_connect_updates'; @@ -77,28 +77,24 @@ function UpdateAlert({api, Wrapper, isCompact, project, organization, className} return null; } - if (appConnectValidationData.appstoreCredentialsValid === false) { - return ( - <div> - {appConnectStoreUpdateAlertMessage}&nbsp; - {isCompact ? ( - <Link to={projectSettingsLink}> - {t('Update it in the project settings to reconnect.')} - </Link> - ) : undefined} - </div> - ); - } - - const commonMessage = isCompact ? ( - <Link to={`${projectSettingsLink}&revalidateItunesSession=true`}> - {t('Update it in the project settings to reconnect.')} - </Link> - ) : undefined; - return ( <div> - {appConnectStoreUpdateAlertMessage}&nbsp;{commonMessage} + {appConnectStoreUpdateAlertMessage}&nbsp; + {isCompact && ( + <Link + to={ + appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.appStoreCredentialsInvalid + ? projectSettingsLink + : `${projectSettingsLink}&revalidateItunesSession=true` + } + > + {appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.isTodayAfterItunesSessionRefreshAt + ? t('We recommend that you update it in the project settings.') + : t('Update it in the project settings to reconnect.')} + </Link> + )} </div> ); } diff --git a/static/app/components/globalAppStoreConnectUpdateAlert/utils.tsx b/static/app/components/globalAppStoreConnectUpdateAlert/utils.tsx index 2dca8e3742baa2..7702fb3437cbda 100644 --- a/static/app/components/globalAppStoreConnectUpdateAlert/utils.tsx +++ b/static/app/components/globalAppStoreConnectUpdateAlert/utils.tsx @@ -1,17 +1,29 @@ import moment from 'moment'; -import {t, tct} from 'app/locale'; +import {t} from 'app/locale'; import {AppStoreConnectValidationData} from 'app/types/debugFiles'; +export const appStoreConnectAlertMessage = { + iTunesSessionInvalid: t( + 'The iTunes session of your configured App Store Connect has expired.' + ), + appStoreCredentialsInvalid: t( + 'The credentials of your configured App Store Connect are invalid.' + ), + isTodayAfterItunesSessionRefreshAt: t( + 'The iTunes session of your configured App Store Connect will likely expire soon.' + ), +}; + export function getAppConnectStoreUpdateAlertMessage( appConnectValidationData: AppStoreConnectValidationData ) { if (appConnectValidationData.itunesSessionValid === false) { - return t('The iTunes session of your configured App Store Connect has expired.'); + return appStoreConnectAlertMessage.iTunesSessionInvalid; } if (appConnectValidationData.appstoreCredentialsValid === false) { - return t('The credentials of your configured App Store Connect are invalid.'); + return appStoreConnectAlertMessage.appStoreCredentialsInvalid; } const itunesSessionRefreshAt = appConnectValidationData.itunesSessionRefreshAt; @@ -20,31 +32,13 @@ export function getAppConnectStoreUpdateAlertMessage( return undefined; } - const foreseenDaysLeftForTheITunesSessionToExpire = moment(itunesSessionRefreshAt).diff( - moment(), - 'days' + const isTodayAfterItunesSessionRefreshAt = moment().isAfter( + moment(itunesSessionRefreshAt) ); - if (foreseenDaysLeftForTheITunesSessionToExpire === 0) { - return t( - 'We recommend that you update the iTunes session of your configured App Store Connect as it will likely expire today.' - ); - } - - if (foreseenDaysLeftForTheITunesSessionToExpire === 1) { - return t( - 'We recommend that you update the iTunes session of your configured App Store Connect as it will likely expire tomorrow.' - ); - } - - if (foreseenDaysLeftForTheITunesSessionToExpire <= 6) { - return tct( - 'We recommend that you update the iTunes session of your configured App Store Connect as it will likely expire in [days] days.', - { - days: foreseenDaysLeftForTheITunesSessionToExpire, - } - ); + if (!isTodayAfterItunesSessionRefreshAt) { + return undefined; } - return undefined; + return appStoreConnectAlertMessage.isTodayAfterItunesSessionRefreshAt; } diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/accordion.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/accordion.tsx deleted file mode 100644 index 4160573b612be5..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/accordion.tsx +++ /dev/null @@ -1,49 +0,0 @@ -import React, {useState} from 'react'; -import styled from '@emotion/styled'; - -import ListItem from 'app/components/list/listItem'; -import {Panel} from 'app/components/panels'; -import {IconChevron} from 'app/icons'; -import space from 'app/styles/space'; - -type Props = { - summary: string; - children: React.ReactNode; - defaultExpanded?: boolean; -}; - -function Accordion({summary, defaultExpanded, children}: Props) { - const [isExpanded, setIsExpanded] = useState(!!defaultExpanded); - - return ( - <ListItem> - <StyledPanel> - <Summary onClick={() => setIsExpanded(!isExpanded)}> - {summary} - <IconChevron direction={isExpanded ? 'down' : 'right'} color="gray400" /> - </Summary> - {isExpanded && <Details>{children}</Details>} - </StyledPanel> - </ListItem> - ); -} - -export default Accordion; - -const StyledPanel = styled(Panel)` - padding: ${space(1.5)}; - margin-bottom: 0; -`; - -const Summary = styled('div')` - display: grid; - grid-template-columns: 1fr max-content; - grid-gap: ${space(1)}; - cursor: pointer; - padding-left: calc(${space(3)} + ${space(1)}); - align-items: center; -`; - -const Details = styled('div')` - padding-top: ${space(1.5)}; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/form.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/form.tsx deleted file mode 100644 index 631a029a0b6437..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/form.tsx +++ /dev/null @@ -1,246 +0,0 @@ -import {Fragment, useState} from 'react'; -import styled from '@emotion/styled'; - -import {addErrorMessage} from 'app/actionCreators/indicator'; -import {Client} from 'app/api'; -import Alert from 'app/components/alert'; -import {IconWarning} from 'app/icons'; -import {t} from 'app/locale'; -import {Organization, Project} from 'app/types'; -import Input from 'app/views/settings/components/forms/controls/input'; -import Textarea from 'app/views/settings/components/forms/controls/textarea'; -import Field from 'app/views/settings/components/forms/field'; -import SelectField from 'app/views/settings/components/forms/selectField'; - -import Stepper from '../stepper'; -import StepActions from '../stepper/stepActions'; -import { - App, - AppStoreCredentialsData, - AppStoreCredentialsStepOneData, - AppStoreCredentialsStepTwoData, -} from '../types'; - -const steps = [t('Enter your credentials'), t('Choose an application')]; - -type Props = { - api: Client; - orgSlug: Organization['slug']; - projectSlug: Project['slug']; - data: AppStoreCredentialsData; - onChange: (data: AppStoreCredentialsData) => void; - onSwitchToReadMode: () => void; - onCancel?: () => void; -}; - -function Form({ - api, - orgSlug, - projectSlug, - data, - onChange, - onCancel, - onSwitchToReadMode, -}: Props) { - const [activeStep, setActiveStep] = useState(0); - const [isLoading, setIsLoading] = useState(false); - - const [appStoreApps, setAppStoreApps] = useState<App[]>([]); - - const [stepOneData, setStepOneData] = useState<AppStoreCredentialsStepOneData>({ - issuer: data.issuer, - keyId: data.keyId, - privateKey: data.privateKey, - }); - - const [stepTwoData, setStepTwoData] = useState<AppStoreCredentialsStepTwoData>({ - app: data.app, - }); - - function isFormInvalid() { - switch (activeStep) { - case 0: - return Object.keys(stepOneData).some(key => !stepOneData[key]); - case 1: - return Object.keys(stepTwoData).some(key => !stepTwoData[key]); - default: - return false; - } - } - - function goNext() { - setActiveStep(prevActiveStep => prevActiveStep + 1); - } - - function handleGoBack() { - setActiveStep(prevActiveStep => prevActiveStep - 1); - } - - function handleGoNext() { - checkAppStoreConnectCredentials(); - } - - function handleSave() { - const updatedData = { - ...stepOneData, - ...stepTwoData, - }; - - onChange(updatedData); - onSwitchToReadMode(); - } - - async function checkAppStoreConnectCredentials() { - setIsLoading(true); - try { - const response = await api.requestPromise( - `/projects/${orgSlug}/${projectSlug}/appstoreconnect/apps/`, - { - method: 'POST', - data: { - appconnectIssuer: stepOneData.issuer, - appconnectKey: stepOneData.keyId, - appconnectPrivateKey: stepOneData.privateKey, - }, - } - ); - - setAppStoreApps(response.apps); - setStepTwoData({app: response.apps[0]}); - setIsLoading(false); - goNext(); - } catch { - setIsLoading(false); - addErrorMessage( - t( - 'We could not establish a connection with App Store Connect. Please check the entered App Store Connect credentials.' - ) - ); - } - } - - function renderStepContent(stepIndex: number) { - switch (stepIndex) { - case 0: - return ( - <Fragment> - <Field - label={t('Issuer')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Input - type="text" - name="issuer" - placeholder={t('Issuer')} - value={stepOneData.issuer} - onChange={e => - setStepOneData({ - ...stepOneData, - issuer: e.target.value, - }) - } - /> - </Field> - <Field - label={t('Key ID')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Input - type="text" - name="keyId" - placeholder={t('Key Id')} - value={stepOneData.keyId} - onChange={e => - setStepOneData({ - ...stepOneData, - keyId: e.target.value, - }) - } - /> - </Field> - <Field - label={t('Private Key')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Textarea - name="privateKey" - placeholder={t('Private Key')} - value={stepOneData.privateKey} - rows={5} - maxRows={5} - autosize - onChange={e => - setStepOneData({ - ...stepOneData, - privateKey: e.target.value, - }) - } - /> - </Field> - </Fragment> - ); - case 1: - return ( - <StyledSelectField - name="application" - label={t('App Store Connect Application')} - choices={appStoreApps.map(appStoreApp => [ - appStoreApp.appId, - appStoreApp.name, - ])} - placeholder={t('Select application')} - onChange={appId => { - const selectedAppStoreApp = appStoreApps.find( - appStoreApp => appStoreApp.appId === appId - ); - setStepTwoData({app: selectedAppStoreApp}); - }} - value={stepTwoData.app?.appId ?? ''} - inline={false} - flexibleControlStateSize - stacked - required - /> - ); - default: - return ( - <Alert type="error" icon={<IconWarning />}> - {t('This step could not be found.')} - </Alert> - ); - } - } - - return ( - <Stepper - activeStep={activeStep} - steps={steps} - renderStepContent={index => renderStepContent(index)} - renderStepActions={index => ( - <StepActions - onGoBack={index !== 0 ? handleGoBack : undefined} - onGoNext={index !== steps.length - 1 ? handleGoNext : undefined} - onCancel={onCancel} - onFinish={handleSave} - primaryButtonDisabled={isFormInvalid() || isLoading} - isLoading={isLoading} - /> - )} - /> - ); -} - -export default Form; - -const StyledSelectField = styled(SelectField)` - padding-right: 0; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/index.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/index.tsx deleted file mode 100644 index 2e3add9db8a59d..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/appStoreCredentials/index.tsx +++ /dev/null @@ -1,62 +0,0 @@ -import {Client} from 'app/api'; -import {t} from 'app/locale'; -import {Organization, Project} from 'app/types'; - -import Card from '../card'; -import CardItem from '../cardItem'; -import {AppStoreCredentialsData} from '../types'; - -import Form from './form'; - -type Props = { - api: Client; - orgSlug: Organization['slug']; - projectSlug: Project['slug']; - isUpdating: boolean; - data: AppStoreCredentialsData; - isEditing: boolean; - onChange: (data: AppStoreCredentialsData) => void; - onEdit: (isEditing: boolean) => void; - onReset: () => void; -}; - -function AppStoreCredentials({ - data, - isUpdating, - onReset, - isEditing, - onEdit, - ...props -}: Props) { - function handleSwitchToReadMode() { - onEdit(false); - } - - function handleCancel() { - onEdit(false); - onReset(); - } - - if (isEditing) { - return ( - <Form - {...props} - data={data} - onSwitchToReadMode={handleSwitchToReadMode} - onCancel={isUpdating ? handleCancel : undefined} - /> - ); - } - - return ( - <Card onEdit={() => onEdit(true)}> - {data.issuer && <CardItem label={t('Issuer')} value={data.issuer} />} - {data.keyId && <CardItem label={t('Key Id')} value={data.keyId} />} - {data.app?.name && ( - <CardItem label={t('App Store Connect Application')} value={data.app?.name} /> - )} - </Card> - ); -} - -export default AppStoreCredentials; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/card.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/card.tsx deleted file mode 100644 index 94deb908dd9935..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/card.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import styled from '@emotion/styled'; - -import Button from 'app/components/button'; -import {IconEdit, IconLock} from 'app/icons'; -import {t} from 'app/locale'; -import space from 'app/styles/space'; - -type Props = { - children: React.ReactNode; - onEdit: () => void; -}; - -function Card({children, onEdit}: Props) { - return ( - <Wrapper> - <IconWrapper> - <IconLock size="lg" /> - </IconWrapper> - <Content>{children}</Content> - <Action> - <Button icon={<IconEdit />} label={t('Edit')} size="small" onClick={onEdit} /> - </Action> - </Wrapper> - ); -} - -export default Card; - -const Wrapper = styled('div')` - display: grid; - grid-template-columns: max-content 1fr max-content; - grid-gap: ${space(1)}; -`; - -const Content = styled('div')` - display: flex; - justify-content: center; - flex-direction: column; - font-size: ${p => p.theme.fontSizeMedium}; -`; - -const IconWrapper = styled('div')` - display: flex; - align-items: center; - padding: 0 ${space(1.5)}; -`; - -const Action = styled('div')` - display: flex; - align-items: center; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/cardItem.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/cardItem.tsx deleted file mode 100644 index 18b3dececd69fd..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/cardItem.tsx +++ /dev/null @@ -1,25 +0,0 @@ -import styled from '@emotion/styled'; - -import space from 'app/styles/space'; - -type Props = { - label: string; - value: string; -}; - -function CardItem({label, value}: Props) { - return ( - <Wrapper> - <strong>{`${label}:`}</strong> - {value} - </Wrapper> - ); -} - -export default CardItem; - -const Wrapper = styled('div')` - display: grid; - grid-template-columns: max-content 1fr; - grid-gap: ${space(1)}; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx index 3c69fb69960b59..9b08ff6c379f70 100644 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/index.tsx @@ -1,6 +1,5 @@ -import {Fragment, useState} from 'react'; +import {Fragment, useEffect, useState} from 'react'; import styled from '@emotion/styled'; -import isEqual from 'lodash/isEqual'; import {addErrorMessage, addSuccessMessage} from 'app/actionCreators/indicator'; import {ModalRenderProps} from 'app/actionCreators/modal'; @@ -8,18 +7,32 @@ import {Client} from 'app/api'; import Alert from 'app/components/alert'; import Button from 'app/components/button'; import ButtonBar from 'app/components/buttonBar'; -import List from 'app/components/list'; -import {IconInfo, IconWarning} from 'app/icons'; -import {t} from 'app/locale'; -import space from 'app/styles/space'; +import { + appStoreConnectAlertMessage, + getAppConnectStoreUpdateAlertMessage, +} from 'app/components/globalAppStoreConnectUpdateAlert/utils'; +import LoadingIndicator from 'app/components/loadingIndicator'; +import {AppStoreConnectContextProps} from 'app/components/projects/appStoreConnectContext'; +import {IconWarning} from 'app/icons'; +import {t, tct} from 'app/locale'; +import space, {ValidSize} from 'app/styles/space'; import {Organization, Project} from 'app/types'; -import {AppStoreConnectValidationData} from 'app/types/debugFiles'; import withApi from 'app/utils/withApi'; -import Accordion from './accordion'; -import AppStoreCredentials from './appStoreCredentials'; -import ItunesCredentials from './itunesCredentials'; -import {AppStoreCredentialsData, ItunesCredentialsData} from './types'; +import StepFifth from './stepFifth'; +import StepFour from './stepFour'; +import StepOne from './stepOne'; +import StepThree from './stepThree'; +import StepTwo from './stepTwo'; +import { + AppleStoreOrg, + AppStoreApp, + StepFifthData, + StepFourData, + StepOneData, + StepThreeData, + StepTwoData, +} from './types'; type IntialData = { appId: string; @@ -38,17 +51,26 @@ type IntialData = { type: string; }; -type Props = Pick<ModalRenderProps, 'Body' | 'Footer' | 'closeModal'> & { +type Props = Pick<ModalRenderProps, 'Header' | 'Body' | 'Footer' | 'closeModal'> & { api: Client; orgSlug: Organization['slug']; projectSlug: Project['slug']; onSubmit: (data: Record<string, any>) => void; revalidateItunesSession: boolean; - appStoreConnectValidationData?: AppStoreConnectValidationData; + appStoreConnectContext?: AppStoreConnectContextProps; initialData?: IntialData; }; +const steps = [ + t('App Store Connect credentials'), + t('Choose an application'), + t('Enter iTunes credentials'), + t('Enter authentication code'), + t('Choose an organization'), +]; + function AppStoreConnect({ + Header, Body, Footer, closeModal, @@ -58,258 +80,502 @@ function AppStoreConnect({ projectSlug, onSubmit, revalidateItunesSession, - appStoreConnectValidationData, + appStoreConnectContext, }: Props) { - const isUpdating = !!initialData; - const appStoreCredentialsInvalid = - appStoreConnectValidationData?.appstoreCredentialsValid === false; - const itunesSessionInvalid = - appStoreConnectValidationData?.itunesSessionValid === false; + const shouldRevalidateItunesSession = + revalidateItunesSession && + (appStoreConnectContext?.itunesSessionValid === false || + appStoreConnectContext?.appstoreCredentialsValid === false); const [isLoading, setIsLoading] = useState(false); - const [isEditingAppStoreCredentials, setIsEditingAppStoreCredentials] = useState( - appStoreCredentialsInvalid || !isUpdating - ); - const [isEditingItunesCredentials, setIsEditingItunesCredentials] = useState( - itunesSessionInvalid || !isUpdating - ); + const [activeStep, setActiveStep] = useState(shouldRevalidateItunesSession ? 2 : 0); + const [appStoreApps, setAppStoreApps] = useState<AppStoreApp[]>([]); + const [appleStoreOrgs, setAppleStoreOrgs] = useState<AppleStoreOrg[]>([]); + const [useSms, setUseSms] = useState(false); + const [sessionContext, setSessionContext] = useState(''); - const appStoreCredentialsInitialData = { + const [stepOneData, setStepOneData] = useState<StepOneData>({ issuer: initialData?.appconnectIssuer, keyId: initialData?.appconnectKey, privateKey: initialData?.appconnectPrivateKey, + }); + + const [stepTwoData, setStepTwoData] = useState<StepTwoData>({ app: - initialData?.appName && initialData?.appId - ? { - appId: initialData.appId, - name: initialData.appName, - } + initialData?.appId && initialData?.appName + ? {appId: initialData.appId, name: initialData.appName} : undefined, - }; + }); - const iTunesCredentialsInitialData = { + const [stepThreeData, setStepThreeData] = useState<StepThreeData>({ username: initialData?.itunesUser, password: initialData?.itunesPassword, + }); + + const [stepFourData, setStepFourData] = useState<StepFourData>({ authenticationCode: undefined, + }); + + const [stepFifthData, setStepFifthData] = useState<StepFifthData>({ org: - initialData?.orgId && initialData?.orgName - ? { - organizationId: initialData.orgId, - name: initialData.appName, - } + initialData?.orgId && initialData?.name + ? {organizationId: initialData.orgId, name: initialData.name} : undefined, - useSms: undefined, - sessionContext: undefined, - }; - - const [ - appStoreCredentialsData, - setAppStoreCredentialsData, - ] = useState<AppStoreCredentialsData>(appStoreCredentialsInitialData); - - const [ - iTunesCredentialsData, - setItunesCredentialsData, - ] = useState<ItunesCredentialsData>(iTunesCredentialsInitialData); - - function isDataInvalid(data: Record<string, any>) { - return Object.keys(data).some(key => { - const value = data[key]; - - if (typeof value === 'string') { - return !value.trim(); - } + }); - return typeof value === 'undefined'; - }); - } + useEffect(() => { + if (shouldRevalidateItunesSession) { + handleStartItunesAuthentication(); + } + }, [shouldRevalidateItunesSession]); - function isAppStoreCredentialsDataInvalid() { - return isDataInvalid(appStoreCredentialsData); - } + async function checkAppStoreConnectCredentials() { + setIsLoading(true); + try { + const response = await api.requestPromise( + `/projects/${orgSlug}/${projectSlug}/appstoreconnect/apps/`, + { + method: 'POST', + data: { + appconnectIssuer: stepOneData.issuer, + appconnectKey: stepOneData.keyId, + appconnectPrivateKey: stepOneData.privateKey, + }, + } + ); - function isItunesCredentialsDataInvalid() { - return isDataInvalid(iTunesCredentialsData); + setAppStoreApps(response.apps); + setStepTwoData({app: response.apps[0]}); + setIsLoading(false); + goNext(); + } catch (error) { + setIsLoading(false); + addErrorMessage( + t( + 'We could not establish a connection with App Store Connect. Please check the entered App Store Connect credentials.' + ) + ); + } } - function isFormInvalid() { - if (!!initialData) { - const isAppStoreCredentialsDataTheSame = isEqual( - appStoreCredentialsData, - appStoreCredentialsInitialData + async function startTwoFactorAuthentication() { + setIsLoading(true); + try { + const response = await api.requestPromise( + `/projects/${orgSlug}/${projectSlug}/appstoreconnect/2fa/`, + { + method: 'POST', + data: { + code: stepFourData.authenticationCode, + useSms, + sessionContext, + }, + } ); - - const isItunesCredentialsDataTheSame = isEqual( - iTunesCredentialsData, - iTunesCredentialsInitialData + setIsLoading(false); + const {organizations, sessionContext: newSessionContext} = response; + setStepFifthData({org: organizations[0]}); + setAppleStoreOrgs(organizations); + setSessionContext(newSessionContext); + goNext(); + } catch (error) { + setIsLoading(false); + addErrorMessage( + t('The two factor authentication failed. Please check the entered code.') ); - - if (!isAppStoreCredentialsDataTheSame && !isItunesCredentialsDataTheSame) { - return isAppStoreCredentialsDataInvalid() && isItunesCredentialsDataInvalid(); - } - - if (!isAppStoreCredentialsDataTheSame) { - return isAppStoreCredentialsDataInvalid(); - } - - if (!isItunesCredentialsDataTheSame) { - return isItunesCredentialsDataInvalid(); - } - - return isAppStoreCredentialsDataTheSame && isItunesCredentialsDataTheSame; } - - return isAppStoreCredentialsDataInvalid() && isItunesCredentialsDataInvalid(); } - async function handleSave() { + async function persistData() { + if (!stepTwoData.app || !stepFifthData.org || !stepThreeData.username) { + return; + } + setIsLoading(true); + let endpoint = `/projects/${orgSlug}/${projectSlug}/appstoreconnect/`; - let successMessage = t('App Store Connect repository was successfully added'); + let successMessage = t('App Store Connect repository was successfully added.'); let errorMessage = t( - 'An error occured while adding the App Store Connect repository' + 'An error occured while adding the App Store Connect repository.' ); if (!!initialData) { endpoint = `${endpoint}${initialData.id}/`; - successMessage = t('App Store Connect repository was successfully updated'); + successMessage = t('App Store Connect repository was successfully updated.'); errorMessage = t( - 'An error occured while updating the App Store Connect repository' + 'An error occured while updating the App Store Connect repository.' ); } - setIsLoading(true); try { const response = await api.requestPromise(endpoint, { method: 'POST', data: { - appconnectIssuer: appStoreCredentialsData.issuer, - appconnectKey: appStoreCredentialsData.keyId, - appconnectPrivateKey: appStoreCredentialsData.privateKey, - appName: appStoreCredentialsData.app?.name, - appId: appStoreCredentialsData.app?.appId, - itunesUser: iTunesCredentialsData.username, - itunesPassword: iTunesCredentialsData.password, - orgId: iTunesCredentialsData.org?.organizationId, - orgName: iTunesCredentialsData.org?.name, - sessionContext: iTunesCredentialsData.sessionContext, + itunesUser: stepThreeData.username, + itunesPassword: stepThreeData.password, + appconnectIssuer: stepOneData.issuer, + appconnectKey: stepOneData.keyId, + appconnectPrivateKey: stepOneData.privateKey, + appName: stepTwoData.app.name, + appId: stepTwoData.app.appId, + orgId: stepFifthData.org.organizationId, + orgName: stepFifthData.org.name, + sessionContext, }, }); addSuccessMessage(successMessage); - setIsLoading(false); onSubmit(response); closeModal(); - } catch { + } catch (error) { setIsLoading(false); addErrorMessage(errorMessage); } } - function handleEditAppStoreCredentials(isEditing: boolean) { + function isFormInvalid() { + switch (activeStep) { + case 0: + return Object.keys(stepOneData).some(key => !stepOneData[key]); + case 1: + return Object.keys(stepTwoData).some(key => !stepTwoData[key]); + case 2: { + return Object.keys(stepThreeData).some(key => !stepThreeData[key]); + } + case 3: { + return Object.keys(stepFourData).some(key => !stepFourData[key]); + } + case 4: { + return Object.keys(stepFifthData).some(key => !stepFifthData[key]); + } + default: + return false; + } + } + + function goNext() { + setActiveStep(activeStep + 1); + } + + async function handleStartItunesAuthentication(shouldGoNext = true) { + if (shouldGoNext) { + setIsLoading(true); + } + if (useSms) { + setUseSms(false); + } + + try { + const response = await api.requestPromise( + `/projects/${orgSlug}/${projectSlug}/appstoreconnect/start/`, + { + method: 'POST', + data: { + itunesUser: stepThreeData.username, + itunesPassword: stepThreeData.password, + }, + } + ); + + setSessionContext(response.sessionContext); + + if (shouldGoNext) { + setIsLoading(false); + goNext(); + } + } catch { + if (shouldGoNext) { + setIsLoading(false); + } + addErrorMessage( + t('The iTunes authentication failed. Please check the entered credentials.') + ); + } + } + + async function handleStartSmsAuthentication() { + if (!useSms) { + setUseSms(true); + } + + try { + const response = await api.requestPromise( + `/projects/${orgSlug}/${projectSlug}/appstoreconnect/requestSms/`, + { + method: 'POST', + data: {sessionContext}, + } + ); + + setSessionContext(response.sessionContext); + } catch { + addErrorMessage(t('An error occured while sending the SMS. Please try again')); + } + } + + function handleGoBack() { + const newActiveStep = activeStep - 1; + + switch (newActiveStep) { + case 3: + handleStartItunesAuthentication(false); + setStepFourData({authenticationCode: undefined}); + break; + default: + break; + } + + setActiveStep(newActiveStep); + } + + function handleGoNext() { + switch (activeStep) { + case 0: + checkAppStoreConnectCredentials(); + break; + case 1: + goNext(); + break; + case 2: + handleStartItunesAuthentication(); + break; + case 3: + startTwoFactorAuthentication(); + break; + case 4: + persistData(); + break; + default: + break; + } + } + + function renderCurrentStep() { + switch (activeStep) { + case 0: + return <StepOne stepOneData={stepOneData} onSetStepOneData={setStepOneData} />; + case 1: + return ( + <StepTwo + appStoreApps={appStoreApps} + stepTwoData={stepTwoData} + onSetStepTwoData={setStepTwoData} + /> + ); + case 2: + return ( + <StepThree stepThreeData={stepThreeData} onSetStepOneData={setStepThreeData} /> + ); + case 3: + return ( + <StepFour + stepFourData={stepFourData} + onSetStepFourData={setStepFourData} + onStartItunesAuthentication={handleStartItunesAuthentication} + onStartSmsAuthentication={handleStartSmsAuthentication} + /> + ); + case 4: + return ( + <StepFifth + appleStoreOrgs={appleStoreOrgs} + stepFifthData={stepFifthData} + onSetStepFifthData={setStepFifthData} + /> + ); + default: + return ( + <Alert type="error" icon={<IconWarning />}> + {t('This step could not be found.')} + </Alert> + ); + } + } + + function getAlerts() { + const alerts: React.ReactElement[] = []; + + const appConnectStoreUpdateAlertMessage = getAppConnectStoreUpdateAlertMessage( + appStoreConnectContext ?? {} + ); + if ( - !isEditing && - isEditingAppStoreCredentials && - isAppStoreCredentialsDataInvalid() + appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.appStoreCredentialsInvalid && + activeStep === 0 ) { - setIsEditingItunesCredentials(true); + alerts.push( + <StyledAlert type="warning" icon={<IconWarning />}> + {t( + 'Your App Store Connect credentials are invalid. To reconnect, update your credentials.' + )} + </StyledAlert> + ); } - setIsEditingAppStoreCredentials(isEditing); + if ( + appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.iTunesSessionInvalid && + activeStep < 3 + ) { + alerts.push( + <StyledAlert type="warning" icon={<IconWarning />}> + {t( + 'Your iTunes session has expired. To reconnect, sign in with your Apple ID and password.' + )} + </StyledAlert> + ); + } + + if ( + appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.iTunesSessionInvalid && + activeStep === 3 + ) { + alerts.push( + <StyledAlert type="warning" icon={<IconWarning />}> + {t('Enter your authentication code to re-validate your iTunes session.')} + </StyledAlert> + ); + } + + if ( + !appConnectStoreUpdateAlertMessage && + revalidateItunesSession && + activeStep === 0 + ) { + alerts.push( + <StyledAlert type="warning" icon={<IconWarning />}> + {t('Your iTunes session has already been re-validated.')} + </StyledAlert> + ); + } + + return alerts; + } + + function renderBodyContent() { + const alerts = getAlerts(); + + return ( + <Fragment> + {!!alerts.length && ( + <Alerts marginBottom={activeStep === 3 ? 1.5 : 3}> + {alerts.map((alert, index) => ( + <Fragment key={index}>{alert}</Fragment> + ))} + </Alerts> + )} + {renderCurrentStep()} + </Fragment> + ); } return ( <Fragment> - <Body> - {revalidateItunesSession && !itunesSessionInvalid && ( - <StyledAlert type="warning" icon={<IconInfo />}> - {t('Your iTunes session has already been re-validated.')} - </StyledAlert> - )} - <StyledList symbol="colored-numeric"> - <Accordion summary={t('App Store Connect credentials')} defaultExpanded> - {appStoreCredentialsInvalid && ( - <StyledAlert type="warning" icon={<IconWarning />}> - {t( - 'Your App Store Connect credentials are invalid. To reconnect, update your credentials.' - )} - </StyledAlert> - )} - <AppStoreCredentials - api={api} - orgSlug={orgSlug} - projectSlug={projectSlug} - data={appStoreCredentialsData} - isUpdating={isUpdating} - isEditing={isEditingAppStoreCredentials} - onChange={setAppStoreCredentialsData} - onReset={() => setAppStoreCredentialsData(appStoreCredentialsInitialData)} - onEdit={handleEditAppStoreCredentials} - /> - </Accordion> - <Accordion - summary={t('iTunes credentials')} - defaultExpanded={ - isUpdating || - itunesSessionInvalid || - (isItunesCredentialsDataInvalid() && !isAppStoreCredentialsDataInvalid()) || - (!isEditingItunesCredentials && !isItunesCredentialsDataInvalid()) - } - > - {!revalidateItunesSession && itunesSessionInvalid && ( - <StyledAlert type="warning" icon={<IconWarning />}> - {t( - 'Your iTunes session has expired. To reconnect, sign in with your Apple ID and password' + <Header closeButton> + <HeaderContent> + <NumericSymbol>{activeStep + 1}</NumericSymbol> + <HeaderContentTitle>{steps[activeStep]}</HeaderContentTitle> + <StepsOverview> + {tct('[currentStep] of [totalSteps]', { + currentStep: activeStep + 1, + totalSteps: steps.length, + })} + </StepsOverview> + </HeaderContent> + </Header> + {initialData && appStoreConnectContext?.isLoading !== false ? ( + <Body> + <LoadingIndicator /> + </Body> + ) : ( + <Fragment> + <Body>{renderBodyContent()}</Body> + <Footer> + <ButtonBar gap={1}> + {activeStep !== 0 && <Button onClick={handleGoBack}>{t('Back')}</Button>} + <StyledButton + priority="primary" + onClick={handleGoNext} + disabled={ + isLoading || + isFormInvalid() || + (appStoreConnectContext + ? appStoreConnectContext?.isLoading !== false + : false) + } + > + {isLoading && ( + <LoadingIndicatorWrapper> + <LoadingIndicator mini /> + </LoadingIndicatorWrapper> )} - </StyledAlert> - )} - <ItunesCredentials - api={api} - orgSlug={orgSlug} - projectSlug={projectSlug} - data={iTunesCredentialsData} - isUpdating={isUpdating} - isEditing={isEditingItunesCredentials} - revalidateItunesSession={revalidateItunesSession && itunesSessionInvalid} - onChange={setItunesCredentialsData} - onReset={() => setItunesCredentialsData(iTunesCredentialsInitialData)} - onEdit={setIsEditingItunesCredentials} - /> - </Accordion> - </StyledList> - </Body> - <Footer> - <ButtonBar gap={1.5}> - <Button onClick={closeModal}>{t('Cancel')}</Button> - <StyledButton - priority="primary" - onClick={handleSave} - disabled={isFormInvalid() || isLoading} - > - {t('Save')} - </StyledButton> - </ButtonBar> - </Footer> + {activeStep + 1 === steps.length + ? initialData + ? t('Update') + : t('Save') + : steps[activeStep + 1]} + </StyledButton> + </ButtonBar> + </Footer> + </Fragment> + )} </Fragment> ); } export default withApi(AppStoreConnect); -const StyledList = styled(List)` - grid-gap: ${space(2)}; - & > li { - padding-left: 0; - :before { - z-index: 1; - left: 9px; - top: ${space(1.5)}; - } - } +const HeaderContent = styled('div')` + display: grid; + grid-template-columns: max-content max-content 1fr; + align-items: center; + grid-gap: ${space(1)}; +`; + +const NumericSymbol = styled('div')` + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + font-weight: 700; + font-size: ${p => p.theme.fontSizeMedium}; + background-color: ${p => p.theme.yellow300}; +`; + +const HeaderContentTitle = styled('div')` + font-weight: 700; + font-size: ${p => p.theme.fontSizeExtraLarge}; +`; + +const StepsOverview = styled('div')` + color: ${p => p.theme.gray300}; + display: flex; + justify-content: flex-end; +`; + +const LoadingIndicatorWrapper = styled('div')` + height: 100%; + position: absolute; + width: 100%; + top: 0; + left: 0; + display: flex; + align-items: center; + justify-content: center; `; const StyledButton = styled(Button)` position: relative; `; +const Alerts = styled('div')<{marginBottom: ValidSize}>` + display: grid; + grid-gap: ${space(1.5)}; + margin-bottom: ${p => space(p.marginBottom)}; +`; + const StyledAlert = styled(Alert)` - margin: ${space(1)} 0 ${space(2)} 0; + margin: 0; `; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/form.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/form.tsx deleted file mode 100644 index 347c86f6c2c78f..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/form.tsx +++ /dev/null @@ -1,367 +0,0 @@ -import {Fragment, useEffect, useState} from 'react'; -import styled from '@emotion/styled'; - -import {addErrorMessage} from 'app/actionCreators/indicator'; -import {Client} from 'app/api'; -import Alert from 'app/components/alert'; -import Button from 'app/components/button'; -import ButtonBar from 'app/components/buttonBar'; -import {IconInfo, IconMobile, IconRefresh, IconWarning} from 'app/icons'; -import {t} from 'app/locale'; -import space from 'app/styles/space'; -import {Organization, Project} from 'app/types'; -import Input from 'app/views/settings/components/forms/controls/input'; -import Field from 'app/views/settings/components/forms/field'; -import SelectField from 'app/views/settings/components/forms/selectField'; - -import Stepper from '../stepper'; -import StepActions from '../stepper/stepActions'; -import { - AppleStoreOrg, - ItunesCredentialsData, - ItunesCredentialsStepOneData, - ItunesCredentialsStepThreeData, - ItunesCredentialsStepTwoData, -} from '../types'; - -const steps = [ - t('Enter your credentials'), - t('Enter your authentication code'), - t('Choose an organization'), -]; - -type Props = { - api: Client; - orgSlug: Organization['slug']; - projectSlug: Project['slug']; - data: ItunesCredentialsData; - revalidateItunesSession: boolean; - onChange: (data: ItunesCredentialsData) => void; - onSwitchToReadMode: () => void; - onCancel?: () => void; -}; - -function Form({ - api, - orgSlug, - projectSlug, - data, - revalidateItunesSession, - onChange, - onSwitchToReadMode, - onCancel, -}: Props) { - const [activeStep, setActiveStep] = useState(0); - const [isLoading, setIsLoading] = useState(false); - const [sessionContext, setSessionContext] = useState(''); - const [useSms, setUseSms] = useState(false); - const [appStoreOrgs, setAppStoreOrgs] = useState<AppleStoreOrg[]>([]); - - const [stepOneData, setSetpOneData] = useState<ItunesCredentialsStepOneData>({ - username: data.username, - password: data.password, - }); - - const [stepTwoData, setStepTwoData] = useState<ItunesCredentialsStepTwoData>({ - authenticationCode: data.authenticationCode, - }); - - const [stepThreeData, setStepThreeData] = useState<ItunesCredentialsStepThreeData>({ - org: data.org, - }); - - useEffect(() => { - if (revalidateItunesSession) { - handleGoNext(); - } - }, [revalidateItunesSession]); - - function isFormInvalid() { - switch (activeStep) { - case 0: - return Object.keys(stepOneData).some(key => !stepOneData[key]); - case 1: - return Object.keys(stepTwoData).some(key => !stepTwoData[key]); - case 2: - return Object.keys(stepThreeData).some(key => !stepThreeData[key]); - default: - return false; - } - } - - function goNext() { - setActiveStep(prevActiveStep => prevActiveStep + 1); - } - - function handleGoBack() { - const newActiveStep = activeStep - 1; - - switch (newActiveStep) { - case 1: - startItunesAuthentication(false); - setStepTwoData({authenticationCode: undefined}); - break; - default: - break; - } - - setActiveStep(newActiveStep); - } - - function handleGoNext() { - switch (activeStep) { - case 0: - startItunesAuthentication(); - break; - case 1: - startTwoFactorAuthentication(); - break; - default: - break; - } - } - - function handleSave() { - onChange({...stepOneData, ...stepTwoData, ...stepThreeData, sessionContext, useSms}); - onSwitchToReadMode(); - } - - async function startItunesAuthentication(shouldGoNext = true) { - if (shouldGoNext) { - setIsLoading(true); - } - if (useSms) { - setUseSms(false); - } - - try { - const response = await api.requestPromise( - `/projects/${orgSlug}/${projectSlug}/appstoreconnect/start/`, - { - method: 'POST', - data: { - itunesUser: stepOneData.username, - itunesPassword: stepOneData.password, - }, - } - ); - - setSessionContext(response.sessionContext); - - if (shouldGoNext) { - setIsLoading(false); - goNext(); - } - } catch { - if (shouldGoNext) { - setIsLoading(false); - } - addErrorMessage( - t('The iTunes authentication failed. Please check the entered credentials.') - ); - } - } - - async function startTwoFactorAuthentication() { - setIsLoading(true); - try { - const response = await api.requestPromise( - `/projects/${orgSlug}/${projectSlug}/appstoreconnect/2fa/`, - { - method: 'POST', - data: { - code: stepTwoData.authenticationCode, - useSms, - sessionContext, - }, - } - ); - setIsLoading(false); - const {organizations, sessionContext: newSessionContext} = response; - setStepThreeData({org: organizations[0]}); - setAppStoreOrgs(organizations); - setSessionContext(newSessionContext); - goNext(); - } catch { - setIsLoading(false); - addErrorMessage( - t('The two factor authentication failed. Please check the entered code.') - ); - } - } - - async function startSmsAuthentication() { - if (!useSms) { - setUseSms(true); - } - - try { - const response = await api.requestPromise( - `/projects/${orgSlug}/${projectSlug}/appstoreconnect/requestSms/`, - { - method: 'POST', - data: {sessionContext}, - } - ); - - setSessionContext(response.sessionContext); - } catch { - addErrorMessage(t('An error occured while sending the SMS. Please try again')); - } - } - - function renderStepContent(stepIndex: number) { - switch (stepIndex) { - case 0: - return ( - <Fragment> - <Field - label={t('Username')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Input - type="text" - name="username" - placeholder={t('Username')} - onChange={e => setSetpOneData({...stepOneData, username: e.target.value})} - /> - </Field> - <Field - label={t('Password')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Input - type="password" - name="password" - placeholder={t('Password')} - onChange={e => setSetpOneData({...stepOneData, password: e.target.value})} - /> - </Field> - </Fragment> - ); - case 1: - return ( - <Fragment> - <StyledAlert type="info" icon={<IconInfo />}> - <AlertContent> - {t('Did not get a verification code?')} - <ButtonBar gap={1}> - <Button - size="small" - title={t('Get a new verification code')} - onClick={() => startItunesAuthentication(false)} - icon={<IconRefresh />} - > - {t('Resend code')} - </Button> - <Button - size="small" - title={t('Get a text message with a code')} - onClick={() => startSmsAuthentication()} - icon={<IconMobile />} - > - {t('Text me')} - </Button> - </ButtonBar> - </AlertContent> - </StyledAlert> - <Field - label={t('Two Factor authentication code')} - inline={false} - flexibleControlStateSize - stacked - required - > - <Input - type="text" - name="two-factor-authentication-code" - placeholder={t('Enter your code')} - value={stepTwoData.authenticationCode} - onChange={e => - setStepTwoData({ - ...setStepTwoData, - authenticationCode: e.target.value, - }) - } - /> - </Field> - </Fragment> - ); - case 2: - return ( - <StyledSelectField - name="organization" - label={t('iTunes Organization')} - choices={appStoreOrgs.map(appStoreOrg => [ - appStoreOrg.organizationId, - appStoreOrg.name, - ])} - placeholder={t('Select organization')} - onChange={organizationId => { - const selectedAppStoreOrg = appStoreOrgs.find( - appStoreOrg => appStoreOrg.organizationId === organizationId - ); - setStepThreeData({org: selectedAppStoreOrg}); - }} - value={stepThreeData.org?.organizationId ?? ''} - inline={false} - flexibleControlStateSize - stacked - required - /> - ); - default: - return ( - <Alert type="error" icon={<IconWarning />}> - {t('This step could not be found.')} - </Alert> - ); - } - } - - return ( - <Stepper - activeStep={activeStep} - steps={steps} - renderStepContent={index => renderStepContent(index)} - renderStepActions={index => ( - <StepActions - onGoBack={index !== 0 ? handleGoBack : undefined} - onGoNext={index !== steps.length - 1 ? handleGoNext : undefined} - onCancel={onCancel} - onFinish={handleSave} - primaryButtonDisabled={isFormInvalid() || isLoading} - isLoading={isLoading} - /> - )} - /> - ); -} - -export default Form; - -const StyledAlert = styled(Alert)` - display: grid; - grid-template-columns: max-content 1fr; - align-items: center; - span:nth-child(2) { - margin: 0; - } -`; - -const AlertContent = styled('div')` - display: grid; - grid-template-columns: 1fr max-content; - align-items: center; - grid-gap: ${space(2)}; -`; - -const StyledSelectField = styled(SelectField)` - padding-right: 0; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/index.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/index.tsx deleted file mode 100644 index d18e18dccbe634..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/itunesCredentials/index.tsx +++ /dev/null @@ -1,64 +0,0 @@ -import {Client} from 'app/api'; -import {t} from 'app/locale'; -import {Organization, Project} from 'app/types'; - -import Card from '../card'; -import CardItem from '../cardItem'; -import {ItunesCredentialsData} from '../types'; - -import Form from './form'; - -type Props = { - api: Client; - orgSlug: Organization['slug']; - projectSlug: Project['slug']; - isUpdating: boolean; - isEditing: boolean; - revalidateItunesSession: boolean; - data: ItunesCredentialsData; - onChange: (data: ItunesCredentialsData) => void; - onEdit: (isEditing: boolean) => void; - onReset: () => void; -}; - -function ItunesCredentials({ - data, - isUpdating, - onReset, - isEditing, - onEdit, - revalidateItunesSession, - ...props -}: Props) { - function handleSwitchToReadMode() { - onEdit(false); - } - - function handleCancel() { - onEdit(false); - onReset(); - } - - if (isEditing) { - return ( - <Form - {...props} - revalidateItunesSession={revalidateItunesSession} - data={data} - onSwitchToReadMode={handleSwitchToReadMode} - onCancel={isUpdating ? handleCancel : undefined} - /> - ); - } - - return ( - <Card onEdit={() => onEdit(true)}> - {data.username && <CardItem label={t('User')} value={data.username} />} - {data.org?.name && ( - <CardItem label={t('iTunes Organization')} value={data.org?.name} /> - )} - </Card> - ); -} - -export default ItunesCredentials; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFifth.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFifth.tsx new file mode 100644 index 00000000000000..d754c7db675b87 --- /dev/null +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFifth.tsx @@ -0,0 +1,43 @@ +import styled from '@emotion/styled'; + +import {t} from 'app/locale'; +import SelectField from 'app/views/settings/components/forms/selectField'; + +import {AppleStoreOrg, StepFifthData} from './types'; + +type Props = { + appleStoreOrgs: AppleStoreOrg[]; + stepFifthData: StepFifthData; + onSetStepFifthData: (stepFifthData: StepFifthData) => void; +}; + +function StepFifth({appleStoreOrgs, stepFifthData, onSetStepFifthData}: Props) { + return ( + <StyledSelectField + name="organization" + label={t('iTunes Organization')} + choices={appleStoreOrgs.map(appleStoreOrg => [ + appleStoreOrg.organizationId, + appleStoreOrg.name, + ])} + placeholder={t('Select organization')} + onChange={organizationId => { + const selectedAppleStoreOrg = appleStoreOrgs.find( + appleStoreOrg => appleStoreOrg.organizationId === organizationId + ); + onSetStepFifthData({org: selectedAppleStoreOrg}); + }} + value={stepFifthData.org?.organizationId ?? ''} + inline={false} + flexibleControlStateSize + stacked + required + /> + ); +} + +export default StepFifth; + +const StyledSelectField = styled(SelectField)` + padding-right: 0; +`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFour.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFour.tsx new file mode 100644 index 00000000000000..fc7d9ad04e31db --- /dev/null +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepFour.tsx @@ -0,0 +1,93 @@ +import {Fragment} from 'react'; +import styled from '@emotion/styled'; + +import Alert from 'app/components/alert'; +import Button from 'app/components/button'; +import ButtonBar from 'app/components/buttonBar'; +import {IconInfo, IconMobile, IconRefresh} from 'app/icons'; +import {t} from 'app/locale'; +import space from 'app/styles/space'; +import Input from 'app/views/settings/components/forms/controls/input'; +import Field from 'app/views/settings/components/forms/field'; + +import {StepFourData} from './types'; + +type Props = { + onStartItunesAuthentication: (startItunesAuthentication: boolean) => void; + onStartSmsAuthentication: () => void; + stepFourData: StepFourData; + onSetStepFourData: (stepFourData: StepFourData) => void; +}; + +function StepFour({ + onStartItunesAuthentication, + onStartSmsAuthentication, + stepFourData, + onSetStepFourData, +}: Props) { + return ( + <Fragment> + <StyledAlert type="info" icon={<IconInfo />}> + <AlertContent> + {t('Did not get a verification code?')} + <ButtonBar gap={1}> + <Button + size="small" + title={t('Get a new verification code')} + onClick={() => onStartItunesAuthentication(false)} + icon={<IconRefresh />} + > + {t('Resend code')} + </Button> + <Button + size="small" + title={t('Get a text message with a code')} + onClick={() => onStartSmsAuthentication()} + icon={<IconMobile />} + > + {t('Text me')} + </Button> + </ButtonBar> + </AlertContent> + </StyledAlert> + <Field + label={t('Two Factor authentication code')} + inline={false} + flexibleControlStateSize + stacked + required + > + <Input + type="text" + name="two-factor-authentication-code" + placeholder={t('Enter your code')} + value={stepFourData.authenticationCode} + onChange={e => + onSetStepFourData({ + ...stepFourData, + authenticationCode: e.target.value, + }) + } + /> + </Field> + </Fragment> + ); +} + +export default StepFour; + +const StyledAlert = styled(Alert)` + display: grid; + grid-template-columns: max-content 1fr; + align-items: center; + span:nth-child(2) { + margin: 0; + } +`; + +const AlertContent = styled('div')` + display: grid; + grid-template-columns: 1fr max-content; + align-items: center; + grid-gap: ${space(2)}; +`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepOne.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepOne.tsx new file mode 100644 index 00000000000000..7ad3a2e49b532d --- /dev/null +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepOne.tsx @@ -0,0 +1,71 @@ +import {Fragment} from 'react'; + +import {t} from 'app/locale'; +import Input from 'app/views/settings/components/forms/controls/input'; +import Textarea from 'app/views/settings/components/forms/controls/textarea'; +import Field from 'app/views/settings/components/forms/field'; + +import {StepOneData} from './types'; + +type Props = { + stepOneData: StepOneData; + onSetStepOneData: (stepOneData: StepOneData) => void; +}; + +function StepOne({stepOneData, onSetStepOneData}: Props) { + return ( + <Fragment> + <Field label={t('Issuer')} inline={false} flexibleControlStateSize stacked required> + <Input + type="text" + name="issuer" + placeholder={t('Issuer')} + value={stepOneData.issuer} + onChange={e => + onSetStepOneData({ + ...stepOneData, + issuer: e.target.value, + }) + } + /> + </Field> + <Field label={t('Key ID')} inline={false} flexibleControlStateSize stacked required> + <Input + type="text" + name="keyId" + placeholder={t('Key Id')} + value={stepOneData.keyId} + onChange={e => + onSetStepOneData({ + ...stepOneData, + keyId: e.target.value, + }) + } + /> + </Field> + <Field + label={t('Private Key')} + inline={false} + flexibleControlStateSize + stacked + required + > + <Textarea + name="privateKey" + placeholder={t('Private Key')} + value={stepOneData.privateKey} + rows={5} + autosize + onChange={e => + onSetStepOneData({ + ...stepOneData, + privateKey: e.target.value, + }) + } + /> + </Field> + </Fragment> + ); +} + +export default StepOne; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepThree.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepThree.tsx new file mode 100644 index 00000000000000..4567101e947c3f --- /dev/null +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepThree.tsx @@ -0,0 +1,49 @@ +import {Fragment} from 'react'; + +import {t} from 'app/locale'; +import Input from 'app/views/settings/components/forms/controls/input'; +import Field from 'app/views/settings/components/forms/field'; + +import {StepThreeData} from './types'; + +type Props = { + stepThreeData: StepThreeData; + onSetStepOneData: (stepThreeData: StepThreeData) => void; +}; + +function StepThree({stepThreeData, onSetStepOneData}: Props) { + return ( + <Fragment> + <Field + label={t('Username')} + inline={false} + flexibleControlStateSize + stacked + required + > + <Input + type="text" + name="username" + placeholder={t('Username')} + onChange={e => onSetStepOneData({...stepThreeData, username: e.target.value})} + /> + </Field> + <Field + label={t('Password')} + inline={false} + flexibleControlStateSize + stacked + required + > + <Input + type="password" + name="password" + placeholder={t('Password')} + onChange={e => onSetStepOneData({...stepThreeData, password: e.target.value})} + /> + </Field> + </Fragment> + ); +} + +export default StepThree; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepTwo.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepTwo.tsx new file mode 100644 index 00000000000000..52e3700e42e554 --- /dev/null +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepTwo.tsx @@ -0,0 +1,40 @@ +import styled from '@emotion/styled'; + +import {t} from 'app/locale'; +import SelectField from 'app/views/settings/components/forms/selectField'; + +import {AppStoreApp, StepTwoData} from './types'; + +type Props = { + appStoreApps: AppStoreApp[]; + stepTwoData: StepTwoData; + onSetStepTwoData: (stepTwoData: StepTwoData) => void; +}; + +function StepTwo({stepTwoData, onSetStepTwoData, appStoreApps}: Props) { + return ( + <StyledSelectField + name="application" + label={t('App Store Connect application')} + choices={appStoreApps.map(appStoreApp => [appStoreApp.appId, appStoreApp.name])} + placeholder={t('Select application')} + onChange={appId => { + const selectedAppStoreApp = appStoreApps.find( + appStoreApp => appStoreApp.appId === appId + ); + onSetStepTwoData({app: selectedAppStoreApp}); + }} + value={stepTwoData.app?.appId ?? ''} + inline={false} + flexibleControlStateSize + stacked + required + /> + ); +} + +export default StepTwo; + +const StyledSelectField = styled(SelectField)` + padding-right: 0; +`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/index.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/index.tsx deleted file mode 100644 index fefc3028ef35c3..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/index.tsx +++ /dev/null @@ -1,57 +0,0 @@ -import {Fragment, useEffect, useRef, useState} from 'react'; - -import Step from './step'; - -type Props = { - activeStep: number; - steps: string[]; - renderStepContent: (stepIndex: number) => React.ReactNode; - renderStepActions: (stepIndex: number) => React.ReactNode; -}; - -function Stepper({activeStep, steps, renderStepContent, renderStepActions}: Props) { - const [stepHeights, setStepHeights] = useState<number[]>([]); - - useEffect(() => { - calcStepContentHeights(); - }, []); - - const wrapperRef = useRef<HTMLDivElement>(null); - - function calcStepContentHeights() { - const stepperElement = wrapperRef.current; - if (stepperElement) { - const newStepHeights = steps.map( - (_step, index) => (stepperElement.children[index] as HTMLDivElement).offsetHeight - ); - - setStepHeights(newStepHeights); - } - } - - return ( - <div ref={wrapperRef}> - {steps.map((step, index) => { - const isActive = !stepHeights.length || activeStep === index; - return ( - <Step - key={step} - label={step} - activeStep={activeStep} - isActive={isActive} - height={!!stepHeights.length ? stepHeights[index] : undefined} - > - {isActive && ( - <Fragment> - {renderStepContent(index)} - {renderStepActions(index)} - </Fragment> - )} - </Step> - ); - })} - </div> - ); -} - -export default Stepper; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/step.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/step.tsx deleted file mode 100644 index 2db27f207da65e..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/step.tsx +++ /dev/null @@ -1,93 +0,0 @@ -import styled from '@emotion/styled'; - -import {IconChevron} from 'app/icons'; -import space from 'app/styles/space'; - -type Props = { - children: React.ReactNode; - label: string; - activeStep: number; - isActive: boolean; - height?: number; -}; - -function Step({children, label, activeStep, isActive, height}: Props) { - return ( - <Wrapper activeStep={activeStep} isActive={isActive} height={height}> - <Connector> - <IconChevron direction="right" size="sm" isCircled /> - </Connector> - <Content> - {label} - {children && <div>{children}</div>} - </Content> - </Wrapper> - ); -} - -export default Step; - -const Connector = styled('div')` - padding: ${space(0.5)} ${space(1.5)} 0 ${space(1.5)}; -`; - -const getHeightStyle = (isActive: boolean, height?: number) => { - if (!height) { - return ''; - } - - if (isActive) { - return ` - height: ${height}px; - `; - } - - return ` - height: 26px; - :not(:last-child) { - height: 42px; - } - `; -}; - -const Wrapper = styled('div')<{activeStep: number; isActive: boolean; height?: number}>` - display: grid; - grid-template-columns: max-content 1fr; - position: relative; - color: ${p => p.theme.gray200}; - margin-left: -${space(1.5)}; - - :not(:last-child) { - padding-bottom: ${space(2)}; - ${Connector} { - :before { - content: ' '; - border-right: 1px ${p => p.theme.gray300} dashed; - position: absolute; - top: 28px; - left: ${space(3)}; - height: calc(100% - 28px); - } - } - - :nth-child(-n + ${p => p.activeStep + 1}) { - ${Connector} { - :before { - border-color: ${p => p.theme.gray500}; - } - } - } - } - - :nth-child(-n + ${p => p.activeStep + 1}) { - color: ${p => p.theme.gray500}; - } - - transition: height 300ms cubic-bezier(0.4, 0, 0.2, 1) 0ms; - ${p => getHeightStyle(p.isActive, p.height)} -`; - -const Content = styled('div')` - display: grid; - grid-gap: ${space(1.5)}; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/stepActions.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/stepActions.tsx deleted file mode 100644 index 80a95c64f2bacc..00000000000000 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/stepper/stepActions.tsx +++ /dev/null @@ -1,91 +0,0 @@ -import styled from '@emotion/styled'; - -import Button from 'app/components/button'; -import ButtonBar from 'app/components/buttonBar'; -import LoadingIndicator from 'app/components/loadingIndicator'; -import {t} from 'app/locale'; - -type Props = { - primaryButtonDisabled: boolean; - isLoading: boolean; - onFinish: () => void; - onCancel?: () => void; - onGoBack?: () => void; - onGoNext?: () => void; -}; - -function StepActions({ - primaryButtonDisabled, - isLoading, - onFinish, - onCancel, - onGoBack, - onGoNext, -}: Props) { - return ( - <Wrapper> - <ButtonBar gap={1}> - {onCancel && ( - <Button size="small" onClick={onCancel}> - {t('Cancel')} - </Button> - )} - {onGoBack && ( - <Button size="small" onClick={onGoBack}> - {t('Back')} - </Button> - )} - {onGoNext ? ( - <StyledButton - size="small" - priority="primary" - onClick={onGoNext} - disabled={primaryButtonDisabled} - > - {isLoading && ( - <LoadingIndicatorWrapper> - <LoadingIndicator mini /> - </LoadingIndicatorWrapper> - )} - {t('Next')} - </StyledButton> - ) : ( - <StyledButton - size="small" - priority="primary" - onClick={onFinish} - disabled={primaryButtonDisabled} - > - {isLoading && ( - <LoadingIndicatorWrapper> - <LoadingIndicator mini /> - </LoadingIndicatorWrapper> - )} - {t('Finish')} - </StyledButton> - )} - </ButtonBar> - </Wrapper> - ); -} - -export default StepActions; - -const Wrapper = styled('div')` - display: flex; -`; - -const StyledButton = styled(Button)` - position: relative; -`; - -const LoadingIndicatorWrapper = styled('div')` - height: 100%; - position: absolute; - width: 100%; - top: 0; - left: 0; - display: flex; - align-items: center; - justify-content: center; -`; diff --git a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/types.tsx b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/types.tsx index 116a982e19e18d..307a08eb29a469 100644 --- a/static/app/components/modals/debugFileCustomRepository/appStoreConnect/types.tsx +++ b/static/app/components/modals/debugFileCustomRepository/appStoreConnect/types.tsx @@ -1,4 +1,4 @@ -export type App = { +export type AppStoreApp = { name: string; appId: string; }; @@ -8,32 +8,25 @@ export type AppleStoreOrg = { organizationId: number; }; -export type AppStoreCredentialsStepOneData = { +export type StepOneData = { issuer?: string; keyId?: string; privateKey?: string; }; -export type AppStoreCredentialsStepTwoData = { - app?: App; +export type StepTwoData = { + app?: AppStoreApp; }; -export type AppStoreCredentialsData = AppStoreCredentialsStepOneData & - AppStoreCredentialsStepTwoData; - -export type ItunesCredentialsStepOneData = { +export type StepThreeData = { username?: string; password?: string; }; -export type ItunesCredentialsStepTwoData = { +export type StepFourData = { authenticationCode?: string; }; -export type ItunesCredentialsStepThreeData = { +export type StepFifthData = { org?: AppleStoreOrg; }; - -export type ItunesCredentialsData = ItunesCredentialsStepOneData & - ItunesCredentialsStepThreeData & - ItunesCredentialsStepTwoData & {sessionContext?: string; useSms?: boolean}; diff --git a/static/app/components/modals/debugFileCustomRepository/index.tsx b/static/app/components/modals/debugFileCustomRepository/index.tsx index 586871dfaf510d..5b7309bfecb50c 100644 --- a/static/app/components/modals/debugFileCustomRepository/index.tsx +++ b/static/app/components/modals/debugFileCustomRepository/index.tsx @@ -53,6 +53,7 @@ function DebugFileCustomRepository({ sourceType, params: {orgId, projectId: projectSlug}, location, + appStoreConnectContext, }: Props) { function handleSave(data: Record<string, string>) { onSave({...data, type: sourceType}); @@ -64,6 +65,7 @@ function DebugFileCustomRepository({ return ( <AppStoreConnect + Header={Header} Body={Body} Footer={Footer} closeModal={closeModal} @@ -72,6 +74,7 @@ function DebugFileCustomRepository({ onSubmit={handleSave} initialData={sourceConfig as AppStoreConnectInitialData | undefined} revalidateItunesSession={!!revalidateItunesSession} + appStoreConnectContext={appStoreConnectContext} /> ); } diff --git a/static/app/components/projects/appStoreConnectContext.tsx b/static/app/components/projects/appStoreConnectContext.tsx index ef0930c8576bcd..2341034f8f1854 100644 --- a/static/app/components/projects/appStoreConnectContext.tsx +++ b/static/app/components/projects/appStoreConnectContext.tsx @@ -68,7 +68,7 @@ const Provider = withApi(({api, children, project, orgSlug}: ProviderProps) => { function getAppStoreConnectSymbolSourceId(symbolSources?: string) { return (symbolSources ? JSON.parse(symbolSources) : []).find( - symbolSource => symbolSource.type === 'appStoreConnect' + symbolSource => symbolSource.type.toLowerCase() === 'appstoreconnect' )?.id; } diff --git a/static/app/views/settings/project/appStoreConnectContext.tsx b/static/app/views/settings/project/appStoreConnectContext.tsx index 9ebf92114621b7..5636966d61d85a 100644 --- a/static/app/views/settings/project/appStoreConnectContext.tsx +++ b/static/app/views/settings/project/appStoreConnectContext.tsx @@ -29,7 +29,7 @@ const Provider = withApi( function getAppStoreConnectSymbolSourceId() { return (project.symbolSources ? JSON.parse(project.symbolSources) : []).find( - symbolSource => symbolSource.type === 'appStoreConnect' + symbolSource => symbolSource.type.toLowerCase() === 'appstoreconnect' )?.id; } diff --git a/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx b/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx index 8a70eb8ffb0bf8..52d9b3ab898f9f 100644 --- a/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx +++ b/static/app/views/settings/projectDebugFiles/externalSources/symbolSources.tsx @@ -12,7 +12,10 @@ import Feature from 'app/components/acl/feature'; import FeatureDisabled from 'app/components/acl/featureDisabled'; import Alert from 'app/components/alert'; import {Item} from 'app/components/dropdownAutoComplete/types'; -import {getAppConnectStoreUpdateAlertMessage} from 'app/components/globalAppStoreConnectUpdateAlert/utils'; +import { + appStoreConnectAlertMessage, + getAppConnectStoreUpdateAlertMessage, +} from 'app/components/globalAppStoreConnectUpdateAlert/utils'; import Link from 'app/components/links/link'; import List from 'app/components/list'; import ListItem from 'app/components/list/listItem'; @@ -48,6 +51,14 @@ function SymbolSources({ }: Props) { const appStoreConnectContext = useContext(AppStoreConnectContext); + const hasSavedAppStoreConnect = symbolSources.find( + symbolSource => symbolSource.type.toLowerCase() === 'appstoreconnect' + ); + + useEffect(() => { + reloadPage(); + }, [hasSavedAppStoreConnect]); + useEffect(() => { openDebugFileSourceDialog(); }, [location.query, appStoreConnectContext]); @@ -74,10 +85,6 @@ function SymbolSources({ }, ]; - const hasSavedAppStoreConnect = symbolSources.find( - symbolSource => symbolSource.type === 'AppStoreConnect' - ); - if ( hasAppConnectStoreFeatureFlag && !hasSavedAppStoreConnect && @@ -90,6 +97,20 @@ function SymbolSources({ }); } + function reloadPage() { + if (!!hasSavedAppStoreConnect || !appStoreConnectContext) { + return; + } + + const appConnectStoreUpdateAlertMessage = getAppConnectStoreUpdateAlertMessage( + appStoreConnectContext + ); + + if (appConnectStoreUpdateAlertMessage) { + window.location.reload(); + } + } + function getRichListFieldValue(): { value: Item[]; warnings?: React.ReactNode[]; @@ -105,7 +126,6 @@ function SymbolSources({ const symbolSourcesWithErrors = symbolSources.map(symbolSource => { if (symbolSource.id === appStoreConnectContext.id) { const appStoreConnectErrors: string[] = []; - let appStoreConnectWarning: React.ReactNode = undefined; const customRepositoryLink = `/settings/${organization.slug}/projects/${projectSlug}/debug-symbols/?customRepository=${symbolSource.id}`; if ( @@ -116,7 +136,10 @@ function SymbolSources({ appStoreConnectContext ); - if (appConnectStoreUpdateAlertMessage) { + if ( + appConnectStoreUpdateAlertMessage === + appStoreConnectAlertMessage.isTodayAfterItunesSessionRefreshAt + ) { symbolSourcesWarnings.push( <div> {appConnectStoreUpdateAlertMessage}{' '} @@ -129,7 +152,11 @@ function SymbolSources({ })} </div> ); - appStoreConnectWarning = appConnectStoreUpdateAlertMessage; + + return { + ...symbolSource, + warning: appConnectStoreUpdateAlertMessage, + }; } } @@ -172,7 +199,6 @@ function SymbolSources({ </StyledList> </Fragment> ) : undefined, - warning: appStoreConnectWarning, }; } @@ -201,8 +227,10 @@ function SymbolSources({ return; } + const {_warning, _error, ...sourceConfig} = item; + openDebugFileSourceModal({ - sourceConfig: item, + sourceConfig, sourceType: item.type, appStoreConnectContext, onSave: updatedData => handleUpdateSymbolSource(updatedData as Item, item.index),
0750603acdd3c5b1f78a1b2697f569f076ea26ac
2021-08-31 13:31:16
Evan Purkhiser
feat(js): Add useApi hook and implement in withApi (#28257)
false
Add useApi hook and implement in withApi (#28257)
feat
diff --git a/static/app/utils/useApi.tsx b/static/app/utils/useApi.tsx new file mode 100644 index 00000000000000..8c312bd6d0b3d8 --- /dev/null +++ b/static/app/utils/useApi.tsx @@ -0,0 +1,48 @@ +import {useEffect, useRef} from 'react'; + +import {Client} from 'app/api'; + +type Options = { + /** + * Enabling this option will disable clearing in-flight requests when the + * component is unmounted. + * + * This may be useful in situations where your component needs to finish up + * somewhere the client was passed into some type of action creator and the + * component is unmounted. + */ + persistInFlight?: boolean; + /** + * An existing API client may be provided. + * + * This is a continent way to re-use clients and still inherit the + * persistInFlight configuration. + */ + api?: Client; +}; + +/** + * Returns an API client that will have it's requests canceled when the owning + * React component is unmounted (may be disabled via options). + */ +function useApi({persistInFlight, api: providedApi}: Options = {}) { + const localApi = useRef<Client>(); + + // Lazily construct the client if we weren't provided with one + if (localApi.current === undefined && providedApi === undefined) { + localApi.current = new Client(); + } + + // Use the provided client if available + const api = providedApi ?? localApi.current!; + + function handleCleanup() { + !persistInFlight && api.clear(); + } + + useEffect(() => handleCleanup, []); + + return api; +} + +export default useApi; diff --git a/static/app/utils/withApi.tsx b/static/app/utils/withApi.tsx index 9d32ca07be7153..410d01717aef8d 100644 --- a/static/app/utils/withApi.tsx +++ b/static/app/utils/withApi.tsx @@ -1,7 +1,6 @@ -import * as React from 'react'; - import {Client} from 'app/api'; import getDisplayName from 'app/utils/getDisplayName'; +import useApi from 'app/utils/useApi'; type InjectedApiProps = { api: Client; @@ -9,46 +8,26 @@ type InjectedApiProps = { type WrappedProps<P> = Omit<P, keyof InjectedApiProps> & Partial<InjectedApiProps>; -type OptionProps = { - /** - * Enabling this option will disable clearing in-flight requests when the - * component is unmounted. - * - * This may be useful in situations where your component needs to finish up - * some where the client was passed into some type of action creator and the - * component is unmounted. - */ - persistInFlight?: boolean; -}; - /** * React Higher-Order Component (HoC) that provides "api" client when mounted, * and clears API requests when component is unmounted. + * + * If an `api` prop is provided when the component is invoked it will be passed + * through. */ const withApi = <P extends InjectedApiProps>( WrappedComponent: React.ComponentType<P>, - {persistInFlight}: OptionProps = {} -) => - class extends React.Component<WrappedProps<P>> { - static displayName = `withApi(${getDisplayName(WrappedComponent)})`; - - constructor(props: WrappedProps<P>) { - super(props); - this.api = new Client(); - } + options: Parameters<typeof useApi>[0] = {} +) => { + const WithApi: React.FC<WrappedProps<P>> = ({api: propsApi, ...props}) => { + const api = useApi({api: propsApi, ...options}); - componentWillUnmount() { - if (!persistInFlight) { - this.api.clear(); - } - } + return <WrappedComponent {...(props as P)} api={api} />; + }; - private api: Client; + WithApi.displayName = `withApi(${getDisplayName(WrappedComponent)})`; - render() { - const {api, ...props} = this.props; - return <WrappedComponent {...({api: api ?? this.api, ...props} as P)} />; - } - }; + return WithApi; +}; export default withApi; diff --git a/tests/js/spec/utils/useApi.spec.tsx b/tests/js/spec/utils/useApi.spec.tsx new file mode 100644 index 00000000000000..cb8729d828aedc --- /dev/null +++ b/tests/js/spec/utils/useApi.spec.tsx @@ -0,0 +1,58 @@ +import {mountWithTheme} from 'sentry-test/reactTestingLibrary'; + +import {Client} from 'app/api'; +import useApi from 'app/utils/useApi'; + +describe('useApi', function () { + let apiInstance: Client; + + type Props = { + /** + * Test passthrough API clients + */ + api?: Client; + /** + * Test persistInFlight + */ + persistInFlight?: boolean; + }; + + const MyComponent: React.FC<Props> = ({api, persistInFlight}) => { + apiInstance = useApi({api, persistInFlight}); + return <div />; + }; + + it('renders MyComponent with an api prop', function () { + mountWithTheme(<MyComponent />); + + expect(apiInstance).toBeInstanceOf(Client); + }); + + it('cancels pending API requests when component is unmounted', function () { + const {unmount} = mountWithTheme(<MyComponent />); + + jest.spyOn(apiInstance, 'clear'); + unmount(); + + expect(apiInstance.clear).toHaveBeenCalled(); + }); + + it('does not cancel inflights when persistInFlight is true', function () { + const {unmount} = mountWithTheme(<MyComponent persistInFlight />); + + jest.spyOn(apiInstance, 'clear'); + unmount(); + + expect(apiInstance.clear).not.toHaveBeenCalled(); + }); + + it('uses pass through API when provided', function () { + const myClient = new Client(); + const {unmount} = mountWithTheme(<MyComponent api={myClient} />); + + jest.spyOn(myClient, 'clear'); + unmount(); + + expect(myClient.clear).toHaveBeenCalled(); + }); +}); diff --git a/tests/js/spec/utils/withApi.spec.jsx b/tests/js/spec/utils/withApi.spec.jsx deleted file mode 100644 index 140fb1ab266828..00000000000000 --- a/tests/js/spec/utils/withApi.spec.jsx +++ /dev/null @@ -1,43 +0,0 @@ -import {mountWithTheme} from 'sentry-test/enzyme'; - -import withApi from 'app/utils/withApi'; - -describe('withApi', function () { - let apiInstance; - const MyComponent = jest.fn(props => { - apiInstance = props.api; - return <div />; - }); - - it('renders MyComponent with an api prop', function () { - const MyComponentWithApi = withApi(MyComponent); - mountWithTheme(<MyComponentWithApi />); - expect(MyComponent).toHaveBeenCalledWith( - expect.objectContaining({ - api: expect.anything(), - }), - expect.anything() - ); - }); - - it('cancels pending API requests when component is unmounted', function () { - const MyComponentWithApi = withApi(MyComponent); - const wrapper = mountWithTheme(<MyComponentWithApi />); - jest.spyOn(apiInstance, 'clear'); - expect(apiInstance.clear).not.toHaveBeenCalled(); - wrapper.unmount(); - expect(apiInstance.clear).toHaveBeenCalled(); - - apiInstance.clear.mockRestore(); - }); - - it('does not cancels pending API requests if persistInFlight is enabled', function () { - const MyComponentWithApi = withApi(MyComponent, {persistInFlight: true}); - const wrapper = mountWithTheme(<MyComponentWithApi />); - jest.spyOn(apiInstance, 'clear'); - wrapper.unmount(); - expect(apiInstance.clear).not.toHaveBeenCalled(); - - apiInstance.clear.mockRestore(); - }); -}); diff --git a/tests/js/spec/utils/withApi.spec.tsx b/tests/js/spec/utils/withApi.spec.tsx new file mode 100644 index 00000000000000..b0119f53f0b31d --- /dev/null +++ b/tests/js/spec/utils/withApi.spec.tsx @@ -0,0 +1,46 @@ +import {mountWithTheme} from 'sentry-test/reactTestingLibrary'; + +import {Client} from 'app/api'; +import withApi from 'app/utils/withApi'; + +describe('withApi', function () { + let apiInstance: Client | undefined; + + type Props = { + /** + * Test passthrough API clients + */ + api?: Client; + }; + + const MyComponent = jest.fn((props: Props) => { + apiInstance = props.api; + return <div />; + }); + + it('renders MyComponent with an api prop', function () { + const MyComponentWithApi = withApi(MyComponent); + mountWithTheme(<MyComponentWithApi />); + + expect(MyComponent).toHaveBeenCalledWith( + expect.objectContaining({api: apiInstance}), + expect.anything() + ); + }); + + it('cancels pending API requests when component is unmounted', async function () { + const MyComponentWithApi = withApi(MyComponent); + const wrapper = mountWithTheme(<MyComponentWithApi />); + + if (apiInstance === undefined) { + throw new Error("apiInstance wasn't defined"); + } + + jest.spyOn(apiInstance, 'clear'); + + expect(apiInstance?.clear).not.toHaveBeenCalled(); + wrapper.unmount(); + + expect(apiInstance?.clear).toHaveBeenCalled(); + }); +});
a4f0cb3a7fcf6b244c26303c56c48d358c3bd47e
2021-01-19 01:14:02
Alberto Leal
feat(dashboardsv2): Expose web vitals and other measurement fields to Dashboards v2 (#23124)
false
Expose web vitals and other measurement fields to Dashboards v2 (#23124)
feat
diff --git a/src/sentry/static/sentry/app/components/modals/addDashboardWidgetModal.tsx b/src/sentry/static/sentry/app/components/modals/addDashboardWidgetModal.tsx index 0ef159f92c27bc..15e1065e55f42e 100644 --- a/src/sentry/static/sentry/app/components/modals/addDashboardWidgetModal.tsx +++ b/src/sentry/static/sentry/app/components/modals/addDashboardWidgetModal.tsx @@ -16,6 +16,7 @@ import {PanelAlert} from 'app/components/panels'; import {t} from 'app/locale'; import space from 'app/styles/space'; import {GlobalSelection, Organization, TagCollection} from 'app/types'; +import Measurements from 'app/utils/measurements/measurements'; import withApi from 'app/utils/withApi'; import withGlobalSelection from 'app/utils/withGlobalSelection'; import withTags from 'app/utils/withTags'; @@ -196,12 +197,12 @@ class AddDashboardWidgetModal extends React.Component<Props, State> { const state = this.state; const errors = state.errors; - // TODO(mark) Figure out how to get measurement keys here. - const fieldOptions = generateFieldOptions({ - organization, - tagKeys: Object.values(tags).map(({key}) => key), - measurementKeys: [], - }); + const fieldOptions = (measurementKeys: string[]) => + generateFieldOptions({ + organization, + tagKeys: Object.values(tags).map(({key}) => key), + measurementKeys, + }); const isUpdatingWidget = typeof onUpdateWidget === 'function' && !!previousWidget; @@ -253,24 +254,34 @@ class AddDashboardWidgetModal extends React.Component<Props, State> { /> </Field> </DoubleFieldWrapper> - {state.queries.map((query, i) => { - return ( - <WidgetQueryForm - key={i} - api={api} - organization={organization} - selection={selection} - fieldOptions={fieldOptions} - widgetQuery={query} - canRemove={state.queries.length > 1} - onRemove={() => this.handleQueryRemove(i)} - onChange={(widgetQuery: WidgetQuery) => - this.handleQueryChange(widgetQuery, i) - } - errors={errors?.queries?.[i]} - /> - ); - })} + <Measurements> + {({measurements}) => { + const measurementKeys = Object.values(measurements).map(({key}) => key); + const amendedFieldOptions = fieldOptions(measurementKeys); + return ( + <React.Fragment> + {state.queries.map((query, i) => { + return ( + <WidgetQueryForm + key={i} + api={api} + organization={organization} + selection={selection} + fieldOptions={amendedFieldOptions} + widgetQuery={query} + canRemove={state.queries.length > 1} + onRemove={() => this.handleQueryRemove(i)} + onChange={(widgetQuery: WidgetQuery) => + this.handleQueryChange(widgetQuery, i) + } + errors={errors?.queries?.[i]} + /> + ); + })} + </React.Fragment> + ); + }} + </Measurements> <WidgetCard api={api} organization={organization}
00c17a25bf86a03302ebc7708096870426a55865
2021-01-05 02:38:06
David Wang
feat(alerts): Add new scopes for editing/viewing alert rules (#22800)
false
Add new scopes for editing/viewing alert rules (#22800)
feat
diff --git a/src/sentry/api/bases/organization.py b/src/sentry/api/bases/organization.py index 285601233cc7af..1e21c8c3a74f45 100644 --- a/src/sentry/api/bases/organization.py +++ b/src/sentry/api/bases/organization.py @@ -141,6 +141,15 @@ class OrganizationDataExportPermission(OrganizationPermission): } +class OrganizationAlertRulePermission(OrganizationPermission): + scope_map = { + "GET": ["org:read", "org:write", "org:admin", "alert_rule:read"], + "POST": ["org:write", "org:admin", "alert_rule:write"], + "PUT": ["org:write", "org:admin", "alert_rule:write"], + "DELETE": ["org:write", "org:admin", "alert_rule:write"], + } + + class OrganizationEndpoint(Endpoint): permission_classes = (OrganizationPermission,) diff --git a/src/sentry/api/bases/project.py b/src/sentry/api/bases/project.py index 78b271599419eb..b8b124760d1797 100644 --- a/src/sentry/api/bases/project.py +++ b/src/sentry/api/bases/project.py @@ -115,6 +115,15 @@ class RelaxedSearchPermission(ProjectPermission): } +class ProjectAlertRulePermission(ProjectPermission): + scope_map = { + "GET": ["project:read", "project:write", "project:admin", "alerts:read"], + "POST": ["project:write", "project:admin", "alerts:write"], + "PUT": ["project:write", "project:admin", "alerts:write"], + "DELETE": ["project:write", "project:admin", "alerts:write"], + } + + class ProjectEndpoint(Endpoint): permission_classes = (ProjectPermission,) diff --git a/src/sentry/api/endpoints/project_rule_details.py b/src/sentry/api/endpoints/project_rule_details.py index 2fc726a34de934..374787ed1c505f 100644 --- a/src/sentry/api/endpoints/project_rule_details.py +++ b/src/sentry/api/endpoints/project_rule_details.py @@ -3,7 +3,7 @@ from rest_framework import status from rest_framework.response import Response -from sentry.api.bases.project import ProjectEndpoint, ProjectSettingPermission +from sentry.api.bases.project import ProjectEndpoint, ProjectAlertRulePermission from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.serializers import serialize from sentry.api.serializers.rest_framework.rule import RuleSerializer @@ -14,7 +14,7 @@ class ProjectRuleDetailsEndpoint(ProjectEndpoint): - permission_classes = [ProjectSettingPermission] + permission_classes = (ProjectAlertRulePermission,) def convert_args(self, request, rule_id, *args, **kwargs): args, kwargs = super(ProjectRuleDetailsEndpoint, self).convert_args( diff --git a/src/sentry/api/endpoints/project_rules.py b/src/sentry/api/endpoints/project_rules.py index 6e78b0edd77de7..135677fdbfc142 100644 --- a/src/sentry/api/endpoints/project_rules.py +++ b/src/sentry/api/endpoints/project_rules.py @@ -4,7 +4,7 @@ from rest_framework import status from rest_framework.response import Response -from sentry.api.bases.project import ProjectEndpoint +from sentry.api.bases.project import ProjectEndpoint, ProjectAlertRulePermission from sentry.api.serializers import serialize from sentry.api.serializers.rest_framework import RuleSerializer from sentry.integrations.slack import tasks @@ -15,6 +15,8 @@ class ProjectRulesEndpoint(ProjectEndpoint): + permission_classes = (ProjectAlertRulePermission,) + @transaction_start("ProjectRulesEndpoint") def get(self, request, project): """ diff --git a/src/sentry/api/serializers/rest_framework/project.py b/src/sentry/api/serializers/rest_framework/project.py index ee526c05baf4ca..d219d830adbe06 100644 --- a/src/sentry/api/serializers/rest_framework/project.py +++ b/src/sentry/api/serializers/rest_framework/project.py @@ -8,6 +8,10 @@ class ProjectField(serializers.Field): + def __init__(self, scope="project:write"): + self.scope = scope + super(ProjectField, self).__init__() + def to_representation(self, value): return value @@ -16,6 +20,6 @@ def to_internal_value(self, data): project = Project.objects.get(organization=self.context["organization"], slug=data) except Project.DoesNotExist: raise ValidationError("Invalid project") - if not self.context["access"].has_project_scope(project, "project:write"): + if not self.context["access"].has_project_scope(project, self.scope): raise ValidationError("Insufficient access to project") return project diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 1be4f610fe990d..0fc760244d12b3 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1283,6 +1283,8 @@ def create_partitioned_queues(name): "event:read", "event:write", "event:admin", + "alerts:write", + "alerts:read", ] ) @@ -1314,6 +1316,7 @@ def create_partitioned_queues(name): ("event:write", "Read and write access to events."), ("event:read", "Read access to events."), ), + (("alerts:write", "Read and write alerts"), ("alerts:read", "Read alerts"),), ) SENTRY_DEFAULT_ROLE = "member" @@ -1337,6 +1340,7 @@ def create_partitioned_queues(name): "org:read", "member:read", "team:read", + "alerts:read", ] ), }, @@ -1362,6 +1366,8 @@ def create_partitioned_queues(name): "team:write", "team:admin", "org:integrations", + "alerts:write", + "alerts:read", ] ), }, @@ -1388,6 +1394,8 @@ def create_partitioned_queues(name): "org:read", "org:write", "org:integrations", + "alerts:write", + "alerts:read", ] ), }, @@ -1416,6 +1424,8 @@ def create_partitioned_queues(name): "event:read", "event:write", "event:admin", + "alerts:write", + "alerts:read", ] ), }, diff --git a/src/sentry/incidents/endpoints/bases.py b/src/sentry/incidents/endpoints/bases.py index 7cd8a008a79e7b..59d1deb62f07cf 100644 --- a/src/sentry/incidents/endpoints/bases.py +++ b/src/sentry/incidents/endpoints/bases.py @@ -3,13 +3,15 @@ from rest_framework.exceptions import PermissionDenied from sentry import features -from sentry.api.bases.project import ProjectEndpoint -from sentry.api.bases.organization import OrganizationEndpoint +from sentry.api.bases.project import ProjectEndpoint, ProjectAlertRulePermission +from sentry.api.bases.organization import OrganizationEndpoint, OrganizationAlertRulePermission from sentry.api.exceptions import ResourceDoesNotExist from sentry.incidents.models import AlertRule, AlertRuleTrigger, AlertRuleTriggerAction class ProjectAlertRuleEndpoint(ProjectEndpoint): + permission_classes = (ProjectAlertRulePermission,) + def convert_args(self, request, alert_rule_id, *args, **kwargs): args, kwargs = super(ProjectAlertRuleEndpoint, self).convert_args(request, *args, **kwargs) project = kwargs["project"] @@ -31,6 +33,8 @@ def convert_args(self, request, alert_rule_id, *args, **kwargs): class OrganizationAlertRuleEndpoint(OrganizationEndpoint): + permission_classes = (OrganizationAlertRulePermission,) + def convert_args(self, request, alert_rule_id, *args, **kwargs): args, kwargs = super(OrganizationAlertRuleEndpoint, self).convert_args( request, *args, **kwargs diff --git a/src/sentry/incidents/endpoints/organization_alert_rule_index.py b/src/sentry/incidents/endpoints/organization_alert_rule_index.py index d5c0084977f014..dc90ba38e76d0b 100644 --- a/src/sentry/incidents/endpoints/organization_alert_rule_index.py +++ b/src/sentry/incidents/endpoints/organization_alert_rule_index.py @@ -4,7 +4,7 @@ from rest_framework.response import Response from sentry import features -from sentry.api.bases.organization import OrganizationEndpoint +from sentry.api.bases.organization import OrganizationEndpoint, OrganizationAlertRulePermission from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.paginator import ( OffsetPaginator, @@ -66,6 +66,8 @@ def get(self, request, organization): class OrganizationAlertRuleIndexEndpoint(OrganizationEndpoint): + permission_classes = (OrganizationAlertRulePermission,) + def get(self, request, organization): """ Fetches alert rules for an organization diff --git a/src/sentry/incidents/endpoints/project_alert_rule_index.py b/src/sentry/incidents/endpoints/project_alert_rule_index.py index c2a3e11088f179..5f3322be0745fc 100644 --- a/src/sentry/incidents/endpoints/project_alert_rule_index.py +++ b/src/sentry/incidents/endpoints/project_alert_rule_index.py @@ -6,7 +6,7 @@ from rest_framework.response import Response from sentry import features -from sentry.api.bases.project import ProjectEndpoint +from sentry.api.bases.project import ProjectEndpoint, ProjectAlertRulePermission from sentry.api.exceptions import ResourceDoesNotExist from sentry.api.paginator import ( OffsetPaginator, @@ -52,6 +52,8 @@ def get(self, request, project): class ProjectAlertRuleIndexEndpoint(ProjectEndpoint): + permission_classes = (ProjectAlertRulePermission,) + def get(self, request, project): """ Fetches alert rules for a project diff --git a/src/sentry/incidents/endpoints/serializers.py b/src/sentry/incidents/endpoints/serializers.py index cf3324d4e41f70..41a985b12f13c8 100644 --- a/src/sentry/incidents/endpoints/serializers.py +++ b/src/sentry/incidents/endpoints/serializers.py @@ -291,8 +291,10 @@ class AlertRuleSerializer(CamelSnakeModelSerializer): environment = EnvironmentField(required=False, allow_null=True) # TODO: These might be slow for many projects, since it will query for each # individually. If we find this to be a problem then we can look into batching. - projects = serializers.ListField(child=ProjectField(), required=False) - excluded_projects = serializers.ListField(child=ProjectField(), required=False) + projects = serializers.ListField(child=ProjectField(scope="project:read"), required=False) + excluded_projects = serializers.ListField( + child=ProjectField(scope="project:read"), required=False + ) triggers = serializers.ListField(required=True) dataset = serializers.CharField(required=False) event_types = serializers.ListField(child=serializers.CharField(), required=False) diff --git a/src/sentry/static/sentry/app/components/createAlertButton.tsx b/src/sentry/static/sentry/app/components/createAlertButton.tsx index 69b11b972823e6..3fbde01618750c 100644 --- a/src/sentry/static/sentry/app/components/createAlertButton.tsx +++ b/src/sentry/static/sentry/app/components/createAlertButton.tsx @@ -336,7 +336,7 @@ const CreateAlertButton = withRouter( } return ( - <Access organization={organization} access={['project:write']}> + <Access organization={organization} access={['alerts:write']}> {({hasAccess}) => ( <Button disabled={!hasAccess} diff --git a/src/sentry/static/sentry/app/constants/index.tsx b/src/sentry/static/sentry/app/constants/index.tsx index 2e8b7132555bd1..dbc1bcd054a9b5 100644 --- a/src/sentry/static/sentry/app/constants/index.tsx +++ b/src/sentry/static/sentry/app/constants/index.tsx @@ -30,6 +30,8 @@ export const API_ACCESS_SCOPES = [ 'member:read', 'member:write', 'member:admin', + 'alerts:read', + 'alerts:write', ] as const; // Default API scopes when adding a new API token or org API token diff --git a/src/sentry/static/sentry/app/views/alerts/rules/row.tsx b/src/sentry/static/sentry/app/views/alerts/rules/row.tsx index ff7aa154647913..70af56d3400577 100644 --- a/src/sentry/static/sentry/app/views/alerts/rules/row.tsx +++ b/src/sentry/static/sentry/app/views/alerts/rules/row.tsx @@ -59,7 +59,7 @@ class RuleListRow extends React.Component<Props, State> { <CreatedBy>{rule?.createdBy?.name ?? '-'}</CreatedBy> <div>{dateCreated}</div> <RightColumn> - <Access access={['project:write']}> + <Access access={['alerts:write']}> {({hasAccess}) => ( <ButtonBar gap={1}> <Confirm diff --git a/src/sentry/static/sentry/app/views/settings/incidentRules/ruleForm/index.tsx b/src/sentry/static/sentry/app/views/settings/incidentRules/ruleForm/index.tsx index 1dab30eedf9f2d..e6d3ddddef38ec 100644 --- a/src/sentry/static/sentry/app/views/settings/incidentRules/ruleForm/index.tsx +++ b/src/sentry/static/sentry/app/views/settings/incidentRules/ruleForm/index.tsx @@ -578,7 +578,7 @@ class RuleFormContainer extends AsyncComponent<Props, State> { ); return ( - <Access access={['project:write']}> + <Access access={['alerts:write']}> {({hasAccess}) => ( <Feature features={['metric-alert-gui-filters']} organization={organization}> {({hasFeature}) => ( diff --git a/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx b/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx index 9ac18e7b1a1e70..56480e2977950a 100644 --- a/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx +++ b/src/sentry/static/sentry/app/views/settings/projectAlerts/issueEditor/index.tsx @@ -435,7 +435,7 @@ class IssueRuleEditor extends AsyncView<Props, State> { // the form with a loading mask on top of it, but force a re-render by using // a different key when we have fetched the rule so that form inputs are filled in return ( - <Access access={['project:write']}> + <Access access={['alerts:write']}> {({hasAccess}) => ( <StyledForm key={isSavedAlertRule(rule) ? rule.id : undefined} diff --git a/tests/js/sentry-test/fixtures/organization.js b/tests/js/sentry-test/fixtures/organization.js index f25c733adb1c5d..7a64a2bb3b66d8 100644 --- a/tests/js/sentry-test/fixtures/organization.js +++ b/tests/js/sentry-test/fixtures/organization.js @@ -15,6 +15,8 @@ export function Organization(params = {}) { 'team:read', 'team:write', 'team:admin', + 'alerts:read', + 'alerts:write', ], status: { id: 'active', diff --git a/tests/js/spec/views/alerts/list/index.spec.jsx b/tests/js/spec/views/alerts/list/index.spec.jsx index 7f894d56035bd8..985ca3587be251 100644 --- a/tests/js/spec/views/alerts/list/index.spec.jsx +++ b/tests/js/spec/views/alerts/list/index.spec.jsx @@ -243,7 +243,7 @@ describe('IncidentsList', function () { ); }); - it('disables the new alert button for members', async function () { + it('disables the new alert button for those without alert:write', async function () { const noAccessOrg = { ...organization, access: [],
c8f02fa8af5cf4e0104891ccf39baee4eb79adcc
2021-01-27 23:52:08
Stephen Cefali
feat(aws-lambda): rename stack name (#23334)
false
rename stack name (#23334)
feat
diff --git a/src/sentry/integrations/aws_lambda/integration.py b/src/sentry/integrations/aws_lambda/integration.py index e0c78254715e16..924111f7607c04 100644 --- a/src/sentry/integrations/aws_lambda/integration.py +++ b/src/sentry/integrations/aws_lambda/integration.py @@ -243,7 +243,7 @@ def render_response(error=None): context = { "baseCloudformationUrl": "https://console.aws.amazon.com/cloudformation/home#/stacks/create/review", "templateUrl": template_url, - "stackName": "Sentry-Monitoring-Stack-Filter", + "stackName": "Sentry-Monitoring-Stack", "regionList": ALL_AWS_REGIONS, "accountNumber": pipeline.fetch_state("account_number"), "region": pipeline.fetch_state("region"), diff --git a/tests/js/spec/views/integrationPipeline/awsLambdaCloudformation.spec.jsx b/tests/js/spec/views/integrationPipeline/awsLambdaCloudformation.spec.jsx index 56472ce52b2621..57c093a6487d44 100644 --- a/tests/js/spec/views/integrationPipeline/awsLambdaCloudformation.spec.jsx +++ b/tests/js/spec/views/integrationPipeline/awsLambdaCloudformation.spec.jsx @@ -18,7 +18,7 @@ describe('AwsLambdaCloudformation', () => { <AwsLambdaCloudformation baseCloudformationUrl="https://console.aws.amazon.com/cloudformation/home#/stacks/create/review" templateUrl="https://example.com/file.json" - stackName="Sentry-Monitoring-Stack-Filter" + stackName="Sentry-Monitoring-Stack" regionList={['us-east-1', 'us-west-1']} accountNumber="" region="" diff --git a/tests/sentry/api/endpoints/test_organization_integration_serverless_functions.py b/tests/sentry/api/endpoints/test_organization_integration_serverless_functions.py index 37b2df5459c6ec..97171b1a28188b 100644 --- a/tests/sentry/api/endpoints/test_organization_integration_serverless_functions.py +++ b/tests/sentry/api/endpoints/test_organization_integration_serverless_functions.py @@ -7,7 +7,7 @@ cloudformation_arn = ( "arn:aws:cloudformation:us-east-2:599817902985:stack/" - "Sentry-Monitoring-Stack-Filter/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" + "Sentry-Monitoring-Stack/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" ) diff --git a/tests/sentry/integrations/aws_lambda/test_integration.py b/tests/sentry/integrations/aws_lambda/test_integration.py index c1f43886b53b73..e206195fbff700 100644 --- a/tests/sentry/integrations/aws_lambda/test_integration.py +++ b/tests/sentry/integrations/aws_lambda/test_integration.py @@ -19,7 +19,7 @@ arn = ( "arn:aws:cloudformation:us-east-2:599817902985:stack/" - "Sentry-Monitoring-Stack-Filter/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" + "Sentry-Monitoring-Stack/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" ) account_number = "599817902985" @@ -61,7 +61,7 @@ def test_render_cloudformation_view(self, mock_react_view): { "baseCloudformationUrl": "https://console.aws.amazon.com/cloudformation/home#/stacks/create/review", "templateUrl": "https://example.com/file.json", - "stackName": "Sentry-Monitoring-Stack-Filter", + "stackName": "Sentry-Monitoring-Stack", "regionList": ALL_AWS_REGIONS, "region": None, "accountNumber": None, @@ -93,7 +93,7 @@ def test_set_arn_with_error(self, mock_react_view, mock_gen_aws_client): { "baseCloudformationUrl": "https://console.aws.amazon.com/cloudformation/home#/stacks/create/review", "templateUrl": "https://example.com/file.json", - "stackName": "Sentry-Monitoring-Stack-Filter", + "stackName": "Sentry-Monitoring-Stack", "regionList": ALL_AWS_REGIONS, "region": region, "accountNumber": account_number, diff --git a/tests/sentry/integrations/aws_lambda/test_utils.py b/tests/sentry/integrations/aws_lambda/test_utils.py index 02a0562091e246..d697960d71afe2 100644 --- a/tests/sentry/integrations/aws_lambda/test_utils.py +++ b/tests/sentry/integrations/aws_lambda/test_utils.py @@ -16,7 +16,7 @@ class ParseArnTest(TestCase): def test_simple(self): arn = ( "arn:aws:cloudformation:us-east-2:599817902985:stack/" - "Sentry-Monitoring-Stack-Filter/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" + "Sentry-Monitoring-Stack/e42083d0-3e3f-11eb-b66a-0ac9b5db7f30" ) parsed = parse_arn(arn) assert parsed["account"] == "599817902985"
771eb7ae469e1a53940320eab1377cef06f41c49
2022-03-28 23:20:52
Sebastian Zivota
feat: Implement rust-minidump stackwalking rate (#32994)
false
Implement rust-minidump stackwalking rate (#32994)
feat
diff --git a/src/sentry/lang/native/symbolicator.py b/src/sentry/lang/native/symbolicator.py index fe5f8d1040e91b..2dd5a8dd1c2688 100644 --- a/src/sentry/lang/native/symbolicator.py +++ b/src/sentry/lang/native/symbolicator.py @@ -404,10 +404,12 @@ def redact_source_secrets(config_sources: json.JSONData) -> json.JSONData: def get_options_for_project(project): compare_rate = options.get("symbolicator.compare_stackwalking_methods_rate") + rust_minidump_stackwalking_rate = options.get("symbolicator.rust_minidump_stackwalking_rate") return { # Symbolicators who do not support options will ignore this field entirely. "dif_candidates": features.has("organizations:images-loaded-v2", project.organization), "compare_stackwalking_methods": random.random() < compare_rate, + "rust_minidump": random.random() < rust_minidump_stackwalking_rate, }
fb15c50854e041d57be9380469ca8c2119ceb3a3
2024-04-24 00:47:50
Ash
feat(perf): Add feature flag for new spans UI (#69506)
false
Add feature flag for new spans UI (#69506)
feat
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 309bea89279082..e3c8a2d5fddcce 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1784,6 +1784,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]: "organizations:performance-streamed-spans-exp-visible": False, # Hides some fields and sections in the transaction summary page that are being deprecated "organizations:performance-transaction-summary-cleanup": False, + # Enables the new UI for span summary and the spans tab + "organizations:performance-spans-new-ui": False, # Enable processing slow issue alerts "organizations:process-slow-alerts": False, # Enable profiling diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py index 4776d7ce6edd5e..a3bdd009fe07a9 100644 --- a/src/sentry/features/temporary.py +++ b/src/sentry/features/temporary.py @@ -166,6 +166,7 @@ def register_temporary_features(manager: FeatureManager): manager.add("organizations:performance-transaction-name-only-search", OrganizationFeature, FeatureHandlerStrategy.REMOTE) manager.add("organizations:performance-transaction-name-only-search-indexed", OrganizationFeature, FeatureHandlerStrategy.REMOTE) manager.add("organizations:performance-transaction-summary-cleanup", OrganizationFeature, FeatureHandlerStrategy.REMOTE) + manager.add("organizations:performance-spans-new-ui", OrganizationFeature, FeatureHandlerStrategy.REMOTE) manager.add("organizations:performance-streamed-spans-exp-ingest", OrganizationFeature, FeatureHandlerStrategy.INTERNAL) manager.add("organizations:performance-streamed-spans-exp-visible", OrganizationFeature, FeatureHandlerStrategy.REMOTE) manager.add("organizations:process-slow-alerts", OrganizationFeature, FeatureHandlerStrategy.INTERNAL)
98cdeb6d3832e2a20bd8910d31118fed0e7ddcd8
2021-12-01 06:44:21
Evan Purkhiser
ref(ui): Give slightly more x padding to tooltips (#30304)
false
Give slightly more x padding to tooltips (#30304)
ref
diff --git a/static/app/components/tooltip.tsx b/static/app/components/tooltip.tsx index 9d8571a331097a..883584a9f3e343 100644 --- a/static/app/components/tooltip.tsx +++ b/static/app/components/tooltip.tsx @@ -326,7 +326,7 @@ const TooltipContent = styled(motion.div)<Pick<Props, 'popperStyle'>>` will-change: transform, opacity; position: relative; background: ${p => p.theme.backgroundElevated}; - padding: ${space(1)}; + padding: ${space(1)} ${space(1.5)}; border-radius: ${p => p.theme.borderRadius}; border: solid 1px ${p => p.theme.border}; box-shadow: ${p => p.theme.dropShadowHeavy};
45ffa10fc133681b0c90b63b43a4e98c8368f5bb
2025-03-06 20:08:31
ArthurKnaus
ref(ddm): Remove analytics definitions (#86478)
false
Remove analytics definitions (#86478)
ref
diff --git a/static/app/utils/analytics.tsx b/static/app/utils/analytics.tsx index 39ae667e8fb9b8..7fca15f02e7807 100644 --- a/static/app/utils/analytics.tsx +++ b/static/app/utils/analytics.tsx @@ -7,8 +7,6 @@ import { alertsEventMap, type AlertsEventParameters, } from 'sentry/utils/analytics/alertsAnalyticsEvents'; -import type {DDMEventParameters} from 'sentry/utils/analytics/ddmAnalyticsEvents'; -import {ddmEventMap} from 'sentry/utils/analytics/ddmAnalyticsEvents'; import { featureFlagEventMap, type FeatureFlagEventParameters, @@ -78,7 +76,6 @@ interface EventParameters AlertsEventParameters, CoreUIEventParameters, DashboardsEventParameters, - DDMEventParameters, DiscoverEventParameters, FeatureFlagEventParameters, FeedbackEventParameters, @@ -109,7 +106,6 @@ const allEventMap: Record<string, string | null> = { ...alertsEventMap, ...coreUIEventMap, ...dashboardsEventMap, - ...ddmEventMap, ...discoverEventMap, ...featureFlagEventMap, ...feedbackEventMap, diff --git a/static/app/utils/analytics/ddmAnalyticsEvents.tsx b/static/app/utils/analytics/ddmAnalyticsEvents.tsx deleted file mode 100644 index c1df65ccae0a46..00000000000000 --- a/static/app/utils/analytics/ddmAnalyticsEvents.tsx +++ /dev/null @@ -1,81 +0,0 @@ -export type DDMEventParameters = { - 'ddm.add-to-dashboard': { - source: 'global' | 'widget'; - }; - 'ddm.code-location': Record<string, unknown>; - 'ddm.create-alert': { - source: 'global' | 'widget'; - }; - 'ddm.open-onboarding': { - source: 'onboarding_panel' | 'header' | 'banner'; - }; - 'ddm.page-view': Record<string, unknown>; - 'ddm.remove-default-query': Record<string, unknown>; - 'ddm.sample-table-interaction': { - target: 'event-id' | 'description' | 'trace-id' | 'profile'; - }; - 'ddm.set-default-query': Record<string, unknown>; - 'ddm.span-metric.create.cancel': Record<string, unknown>; - 'ddm.span-metric.create.open': { - source: string; - }; - 'ddm.span-metric.create.success': { - hasFilters: boolean; - }; - 'ddm.span-metric.delete': Record<string, unknown>; - 'ddm.span-metric.edit.cancel': Record<string, unknown>; - 'ddm.span-metric.edit.open': { - hasFilters: boolean; - source: string; - }; - 'ddm.span-metric.edit.success': { - hasFilters: boolean; - }; - 'ddm.span-metric.form.add-filter': Record<string, unknown>; - 'ddm.span-metric.form.remove-filter': Record<string, unknown>; - 'ddm.view_performance_metrics': Record<string, unknown>; - 'ddm.widget.add': { - type: 'query' | 'equation'; - }; - 'ddm.widget.condition': Record<string, unknown>; - 'ddm.widget.duplicate': Record<string, unknown>; - 'ddm.widget.filter': Record<string, unknown>; - 'ddm.widget.group': Record<string, unknown>; - 'ddm.widget.metric': Record<string, unknown>; - 'ddm.widget.metric-settings': Record<string, unknown>; - 'ddm.widget.operation': Record<string, unknown>; - 'ddm.widget.sort': { - by: string; - order: string; - }; -}; - -export const ddmEventMap: Record<keyof DDMEventParameters, string> = { - 'ddm.page-view': 'DDM: Page View', - 'ddm.remove-default-query': 'DDM: Remove Default Query', - 'ddm.set-default-query': 'DDM: Set Default Query', - 'ddm.open-onboarding': 'DDM: Open Onboarding', - 'ddm.view_performance_metrics': 'DDM: View Performance Metrics', - 'ddm.widget.add': 'DDM: Widget Added', - 'ddm.widget.sort': 'DDM: Group By Sort Changed', - 'ddm.widget.duplicate': 'DDM: Widget Duplicated', - 'ddm.widget.metric-settings': 'DDM: Widget Metric Settings', - 'ddm.create-alert': 'DDM: Create Alert', - 'ddm.add-to-dashboard': 'DDM: Add to Dashboard', - 'ddm.code-location': 'DDM: Code Location', - 'ddm.sample-table-interaction': 'DDM: Sample Table Interaction', - 'ddm.widget.filter': 'DDM: Change query filter', - 'ddm.widget.group': 'DDM: Change query grouping', - 'ddm.widget.metric': 'DDM: Change query metric', - 'ddm.widget.operation': 'DDM: Change query operation', - 'ddm.widget.condition': 'DDM: Change query condition', - 'ddm.span-metric.create.cancel': 'DDM: Cancel span metric create', - 'ddm.span-metric.create.open': 'DDM: Open span metric create', - 'ddm.span-metric.create.success': 'DDM: Created span metric', - 'ddm.span-metric.delete': 'DDM: Delete span metric', - 'ddm.span-metric.edit.cancel': 'DDM: Cancel span metric edit', - 'ddm.span-metric.edit.open': 'DDM: Open span metric edit', - 'ddm.span-metric.edit.success': 'DDM: Edited span metric', - 'ddm.span-metric.form.add-filter': 'DDM: Add filter in span metric form', - 'ddm.span-metric.form.remove-filter': 'DDM: Remove filter in span metric form', -};
f6b822bdeaeedcdbccdc51a6d009843f59ff758c
2022-04-29 14:35:15
Joris Bayer
feat(metrics): Add derived metrics for crash rate (#34044)
false
Add derived metrics for crash rate (#34044)
feat
diff --git a/src/sentry/snuba/metrics/fields/base.py b/src/sentry/snuba/metrics/fields/base.py index 185b66895f1347..d878b4c655bc14 100644 --- a/src/sentry/snuba/metrics/fields/base.py +++ b/src/sentry/snuba/metrics/fields/base.py @@ -44,6 +44,7 @@ all_transactions, all_users, apdex, + complement, crashed_sessions, crashed_users, division_float, @@ -51,7 +52,6 @@ errored_preaggr_sessions, failure_count_transaction, miserable_users, - percentage, satisfaction_count_transaction, session_duration_filters, subtraction, @@ -865,19 +865,31 @@ def run_post_query_function( ), ), SingularEntityDerivedMetric( - metric_mri=SessionMRI.CRASH_FREE_RATE.value, + metric_mri=SessionMRI.CRASH_RATE.value, metrics=[SessionMRI.CRASHED.value, SessionMRI.ALL.value], unit="percentage", - snql=lambda *args, org_id, metric_ids, alias=None: percentage(*args, alias=alias), + snql=lambda *args, org_id, metric_ids, alias=None: division_float(*args, alias=alias), ), SingularEntityDerivedMetric( - metric_mri=SessionMRI.CRASH_FREE_USER_RATE.value, + metric_mri=SessionMRI.CRASH_USER_RATE.value, metrics=[ SessionMRI.CRASHED_USER.value, SessionMRI.ALL_USER.value, ], unit="percentage", - snql=lambda *args, org_id, metric_ids, alias=None: percentage(*args, alias=alias), + snql=lambda *args, org_id, metric_ids, alias=None: division_float(*args, alias=alias), + ), + SingularEntityDerivedMetric( + metric_mri=SessionMRI.CRASH_FREE_RATE.value, + metrics=[SessionMRI.CRASH_RATE.value], + unit="percentage", + snql=lambda *args, org_id, metric_ids, alias=None: complement(*args, alias=alias), + ), + SingularEntityDerivedMetric( + metric_mri=SessionMRI.CRASH_FREE_USER_RATE.value, + metrics=[SessionMRI.CRASH_USER_RATE.value], + unit="percentage", + snql=lambda *args, org_id, metric_ids, alias=None: complement(*args, alias=alias), ), SingularEntityDerivedMetric( metric_mri=SessionMRI.ERRORED_PREAGGREGATED.value, diff --git a/src/sentry/snuba/metrics/fields/snql.py b/src/sentry/snuba/metrics/fields/snql.py index 11771171c31638..c407b8188edb52 100644 --- a/src/sentry/snuba/metrics/fields/snql.py +++ b/src/sentry/snuba/metrics/fields/snql.py @@ -258,10 +258,6 @@ def miserable_users(org_id, metric_ids, alias=None): ) -def percentage(arg1_snql, arg2_snql, alias=None): - return Function("minus", [1, Function("divide", [arg1_snql, arg2_snql])], alias) - - def subtraction(arg1_snql, arg2_snql, alias=None): return Function("minus", [arg1_snql, arg2_snql], alias) @@ -280,6 +276,11 @@ def division_float(arg1_snql, arg2_snql, alias=None): ) +def complement(arg1_snql, alias=None): + """(x) -> (1 - x)""" + return Function("minus", [1.0, arg1_snql], alias=alias) + + def session_duration_filters(org_id): return [ Function( diff --git a/src/sentry/snuba/metrics/naming_layer/mri.py b/src/sentry/snuba/metrics/naming_layer/mri.py index ef90a4f227516b..f83bd699e7a526 100644 --- a/src/sentry/snuba/metrics/naming_layer/mri.py +++ b/src/sentry/snuba/metrics/naming_layer/mri.py @@ -38,6 +38,7 @@ class SessionMRI(Enum): CRASHED_AND_ABNORMAL = "e:sessions/crashed_abnormal@none" CRASHED = "e:sessions/crashed@none" ABNORMAL = "e:sessions/abnormal@none" + CRASH_RATE = "e:sessions/crash_rate@ratio" CRASH_FREE_RATE = "e:sessions/crash_free_rate@ratio" ALL_USER = "e:sessions/user.all@none" HEALTHY_USER = "e:sessions/user.healthy@none" @@ -46,6 +47,7 @@ class SessionMRI(Enum): CRASHED_AND_ABNORMAL_USER = "e:sessions/user.crashed_abnormal@none" CRASHED_USER = "e:sessions/user.crashed@none" ABNORMAL_USER = "e:sessions/user.abnormal@none" + CRASH_USER_RATE = "e:sessions/user.crash_rate@ratio" CRASH_FREE_USER_RATE = "e:sessions/user.crash_free_rate@ratio" DURATION = "d:sessions/duration.exited@second" diff --git a/src/sentry/snuba/metrics/naming_layer/public.py b/src/sentry/snuba/metrics/naming_layer/public.py index 6cf1044ecfd331..2fdd58ae696be3 100644 --- a/src/sentry/snuba/metrics/naming_layer/public.py +++ b/src/sentry/snuba/metrics/naming_layer/public.py @@ -32,12 +32,14 @@ class SessionMetricKey(Enum): CRASHED = "session.crashed" ERRORED = "session.errored" HEALTHY = "session.healthy" + CRASH_RATE = "session.crash_rate" CRASH_FREE_RATE = "session.crash_free_rate" ALL_USER = "session.all_user" ABNORMAL_USER = "session.abnormal_user" CRASHED_USER = "session.crashed_user" ERRORED_USER = "session.errored_user" HEALTHY_USER = "session.healthy_user" + CRASH_USER_RATE = "session.crash_user_rate" CRASH_FREE_USER_RATE = "session.crash_free_user_rate" diff --git a/tests/sentry/api/endpoints/test_organization_metric_data.py b/tests/sentry/api/endpoints/test_organization_metric_data.py index b09be438a44963..b28913775b9e20 100644 --- a/tests/sentry/api/endpoints/test_organization_metric_data.py +++ b/tests/sentry/api/endpoints/test_organization_metric_data.py @@ -1591,7 +1591,12 @@ def test_crash_free_user_rate_orderby_crash_free_rate(self): response = self.get_success_response( self.organization.slug, - field=["session.crash_free_user_rate", "session.crash_free_rate"], + field=[ + "session.crash_free_user_rate", + "session.crash_free_rate", + "session.crash_user_rate", + "session.crash_rate", + ], statsPeriod="1h", interval="1h", groupBy="release", @@ -1601,11 +1606,15 @@ def test_crash_free_user_rate_orderby_crash_free_rate(self): assert group["by"]["release"] == "[email protected]" assert group["totals"]["session.crash_free_rate"] == 0.75 assert group["totals"]["session.crash_free_user_rate"] == 0.5 + assert group["totals"]["session.crash_rate"] == 0.25 + assert group["totals"]["session.crash_user_rate"] == 0.5 group = response.data["groups"][1] assert group["by"]["release"] == "[email protected]" assert group["totals"]["session.crash_free_rate"] == 0.25 assert group["totals"]["session.crash_free_user_rate"] == 1.0 + assert group["totals"]["session.crash_rate"] == 0.75 + assert group["totals"]["session.crash_user_rate"] == 0.0 def test_healthy_sessions(self): user_ts = time.time() diff --git a/tests/sentry/api/endpoints/test_organization_metric_details.py b/tests/sentry/api/endpoints/test_organization_metric_details.py index 7b6a7f1916237e..1f8193f8bfc13a 100644 --- a/tests/sentry/api/endpoints/test_organization_metric_details.py +++ b/tests/sentry/api/endpoints/test_organization_metric_details.py @@ -3,7 +3,8 @@ from unittest.mock import patch from sentry.sentry_metrics import indexer -from sentry.snuba.metrics import SingularEntityDerivedMetric, percentage, resolve_weak +from sentry.snuba.metrics import SingularEntityDerivedMetric, resolve_weak +from sentry.snuba.metrics.fields.snql import complement, division_float from sentry.snuba.metrics.naming_layer.mapping import get_mri, get_public_name_from_mri from sentry.snuba.metrics.naming_layer.mri import SessionMRI from sentry.snuba.metrics.naming_layer.public import SessionMetricKey @@ -20,8 +21,8 @@ metric_mri="derived_metric.multiple_metrics", metrics=["metric_foo_doe", SessionMRI.ALL.value], unit="percentage", - snql=lambda *args, metric_ids, alias=None: percentage( - *args, alias=SessionMetricKey.CRASH_FREE_RATE.value + snql=lambda *args, metric_ids, alias=None: complement( + division_float(*args), alias=SessionMetricKey.CRASH_FREE_RATE.value ), ) } diff --git a/tests/sentry/api/endpoints/test_organization_metrics.py b/tests/sentry/api/endpoints/test_organization_metrics.py index 91d72a32c29e95..53d34fb2c80929 100644 --- a/tests/sentry/api/endpoints/test_organization_metrics.py +++ b/tests/sentry/api/endpoints/test_organization_metrics.py @@ -13,7 +13,7 @@ SingularEntityDerivedMetric, TransactionSatisfactionTagValue, ) -from sentry.snuba.metrics.fields.snql import percentage +from sentry.snuba.metrics.fields.snql import complement, division_float from sentry.snuba.metrics.naming_layer.mapping import get_public_name_from_mri from sentry.snuba.metrics.naming_layer.mri import SessionMRI, TransactionMRI from sentry.testutils import APITestCase @@ -29,8 +29,8 @@ SessionMRI.ERRORED_SET.value, ], unit="percentage", - snql=lambda *args, entity, metric_ids, alias=None: percentage( - *args, entity, metric_ids, alias="crash_free_fake" + snql=lambda *args, entity, metric_ids, alias=None: complement( + division_float(*args, entity, metric_ids), alias="crash_free_fake" ), ) } @@ -114,6 +114,18 @@ def setUp(self): "operations": [], "unit": "percentage", }, + { + "name": "session.crash_rate", + "type": "numeric", + "operations": [], + "unit": "percentage", + }, + { + "name": "session.crash_user_rate", + "type": "numeric", + "operations": [], + "unit": "percentage", + }, {"name": "session.crashed", "type": "numeric", "operations": [], "unit": "sessions"}, {"name": "session.crashed_user", "type": "numeric", "operations": [], "unit": "users"}, { diff --git a/tests/sentry/snuba/metrics/fields/test_base.py b/tests/sentry/snuba/metrics/fields/test_base.py index ba05281e7f463c..beaceb95b82025 100644 --- a/tests/sentry/snuba/metrics/fields/test_base.py +++ b/tests/sentry/snuba/metrics/fields/test_base.py @@ -22,11 +22,12 @@ addition, all_sessions, all_users, + complement, crashed_sessions, crashed_users, + division_float, errored_all_users, errored_preaggr_sessions, - percentage, subtraction, uniq_aggregation_on_metric, ) @@ -52,8 +53,8 @@ def get_entity_of_metric_mocked(_, metric_mri): metric_mri="crash_free_fake", metrics=[SessionMRI.CRASHED.value, SessionMRI.ERRORED_SET.value], unit="percentage", - snql=lambda *args, org_id, metric_ids, alias=None: percentage( - *args, metric_ids, alias="crash_free_fake" + snql=lambda *args, org_id, metric_ids, alias=None: complement( + division_float(*args, metric_ids, alias="crash_free_fake") ), ), "random_composite": CompositeEntityDerivedMetric( @@ -203,20 +204,28 @@ def test_generate_select_snql_of_derived_metric(self): assert MOCKED_DERIVED_METRICS[SessionMRI.CRASH_FREE_RATE.value].generate_select_statements( [self.project], query_definition=query_definition ) == [ - percentage( - crashed_sessions(org_id, metric_ids=session_ids, alias=SessionMRI.CRASHED.value), - all_sessions(org_id, metric_ids=session_ids, alias=SessionMRI.ALL.value), + complement( + division_float( + crashed_sessions( + org_id, metric_ids=session_ids, alias=SessionMRI.CRASHED.value + ), + all_sessions(org_id, metric_ids=session_ids, alias=SessionMRI.ALL.value), + alias="e:sessions/crash_rate@ratio", + ), alias=SessionMRI.CRASH_FREE_RATE.value, ) ] assert MOCKED_DERIVED_METRICS[ SessionMRI.CRASH_FREE_USER_RATE.value ].generate_select_statements([self.project], query_definition=query_definition) == [ - percentage( - crashed_users( - org_id, metric_ids=session_user_ids, alias=SessionMRI.CRASHED_USER.value + complement( + division_float( + crashed_users( + org_id, metric_ids=session_user_ids, alias=SessionMRI.CRASHED_USER.value + ), + all_users(org_id, metric_ids=session_user_ids, alias=SessionMRI.ALL_USER.value), + alias=SessionMRI.CRASH_USER_RATE.value, ), - all_users(org_id, metric_ids=session_user_ids, alias=SessionMRI.ALL_USER.value), alias=SessionMRI.CRASH_FREE_USER_RATE.value, ) ] diff --git a/tests/sentry/snuba/metrics/test_query_builder.py b/tests/sentry/snuba/metrics/test_query_builder.py index 8fd9192324cd57..198fd4863983bc 100644 --- a/tests/sentry/snuba/metrics/test_query_builder.py +++ b/tests/sentry/snuba/metrics/test_query_builder.py @@ -42,9 +42,10 @@ abnormal_sessions, addition, all_sessions, + complement, crashed_sessions, + division_float, errored_preaggr_sessions, - percentage, uniq_aggregation_on_metric, ) from sentry.snuba.metrics.naming_layer.mapping import get_mri @@ -438,16 +439,19 @@ def test_build_snuba_query_derived_metrics(mock_now, mock_now2, monkeypatch): ), alias=SessionMRI.CRASHED_AND_ABNORMAL.value, ), - percentage( - crashed_sessions( - org_id, - metric_ids=[resolve_weak(org_id, SessionMRI.SESSION.value)], - alias=SessionMRI.CRASHED.value, - ), - all_sessions( - org_id, - metric_ids=[resolve_weak(org_id, SessionMRI.SESSION.value)], - alias=SessionMRI.ALL.value, + complement( + division_float( + crashed_sessions( + org_id, + metric_ids=[resolve_weak(org_id, SessionMRI.SESSION.value)], + alias=SessionMRI.CRASHED.value, + ), + all_sessions( + org_id, + metric_ids=[resolve_weak(org_id, SessionMRI.SESSION.value)], + alias=SessionMRI.ALL.value, + ), + alias=SessionMRI.CRASH_RATE.value, ), alias=SessionMRI.CRASH_FREE_RATE.value, ), diff --git a/tests/sentry/snuba/metrics/test_snql.py b/tests/sentry/snuba/metrics/test_snql.py index 4066a8750d10c6..e4520c2109a620 100644 --- a/tests/sentry/snuba/metrics/test_snql.py +++ b/tests/sentry/snuba/metrics/test_snql.py @@ -14,12 +14,12 @@ crashed_users, errored_all_users, errored_preaggr_sessions, - percentage, session_duration_filters, subtraction, uniq_aggregation_on_metric, ) from sentry.snuba.metrics.fields.snql import ( + complement, division_float, failure_count_transaction, miserable_users, @@ -297,14 +297,9 @@ def test_dist_count_aggregation_on_tx_satisfaction(self): alias="transaction.tolerated", ) - def test_percentage_in_snql(self): - alias = "foo.percentage" - init_session_snql = all_sessions(self.org_id, self.metric_ids, "init_sessions") - crashed_session_snql = crashed_sessions(self.org_id, self.metric_ids, "crashed_sessions") - - assert percentage(crashed_session_snql, init_session_snql, alias=alias) == Function( - "minus", [1, Function("divide", [crashed_session_snql, init_session_snql])], alias - ) + def test_complement_in_sql(self): + alias = "foo.complement" + assert complement(0.64, alias=alias) == Function("minus", [1, 0.64], alias) def test_addition_in_snql(self): alias = "session.crashed_and_abnormal_user"
234859ed9de1a7b16b21647797901d303fba0564
2022-03-24 03:29:06
Evan Purkhiser
feat(ui): Indicate when org is pending deletion in the dropdown (#32856)
false
Indicate when org is pending deletion in the dropdown (#32856)
feat
diff --git a/static/app/components/sidebar/sidebarDropdown/index.tsx b/static/app/components/sidebar/sidebarDropdown/index.tsx index adde8fc580180d..5f2f32bfbc899f 100644 --- a/static/app/components/sidebar/sidebarDropdown/index.tsx +++ b/static/app/components/sidebar/sidebarDropdown/index.tsx @@ -211,7 +211,7 @@ const SidebarDropdownRoot = styled('div')` // So that long org names and user names do not overflow const OrgAndUserWrapper = styled('div')` - overflow: hidden; + overflow-x: hidden; text-align: left; `; const OrgOrUserName = styled(TextOverflow)` diff --git a/static/app/components/sidebar/sidebarDropdown/switchOrganization.tsx b/static/app/components/sidebar/sidebarDropdown/switchOrganization.tsx index ef6cdfc5159a2a..9abcba78ddac5a 100644 --- a/static/app/components/sidebar/sidebarDropdown/switchOrganization.tsx +++ b/static/app/components/sidebar/sidebarDropdown/switchOrganization.tsx @@ -1,5 +1,6 @@ import {Fragment} from 'react'; import styled from '@emotion/styled'; +import sortBy from 'lodash/sortBy'; import DropdownMenu from 'sentry/components/dropdownMenu'; import SidebarDropdownMenu from 'sentry/components/sidebar/sidebarDropdownMenu.styled'; @@ -49,8 +50,8 @@ const SwitchOrganization = ({organizations, canCreateOrganization}: Props) => ( data-test-id="sidebar-switch-org-menu" {...getMenuProps({})} > - <OrganizationList> - {organizations.map(organization => { + <OrganizationList role="list"> + {sortBy(organizations, ['status.id']).map(organization => { const url = `/organizations/${organization.slug}/`; return ( diff --git a/static/app/components/sidebar/sidebarMenuItem.tsx b/static/app/components/sidebar/sidebarMenuItem.tsx index e0d968284dd2d0..7d8b0d8b969a9f 100644 --- a/static/app/components/sidebar/sidebarMenuItem.tsx +++ b/static/app/components/sidebar/sidebarMenuItem.tsx @@ -5,7 +5,7 @@ import styled from '@emotion/styled'; import {Theme} from 'sentry/utils/theme'; import SidebarMenuItemLink from './sidebarMenuItemLink'; -import {OrgSummary} from './sidebarOrgSummary'; +import SidebarOrgSummary from './sidebarOrgSummary'; type Props = { children: React.ReactNode; @@ -41,7 +41,7 @@ const menuItemStyles = ( outline: none; } - ${OrgSummary} { + ${SidebarOrgSummary} { padding-left: 0; padding-right: 0; } diff --git a/static/app/components/sidebar/sidebarOrgSummary.tsx b/static/app/components/sidebar/sidebarOrgSummary.tsx index 3820aca5f4fd28..364b082f8384ac 100644 --- a/static/app/components/sidebar/sidebarOrgSummary.tsx +++ b/static/app/components/sidebar/sidebarOrgSummary.tsx @@ -1,6 +1,7 @@ import styled from '@emotion/styled'; import OrganizationAvatar from 'sentry/components/avatar/organizationAvatar'; +import {IconWarning} from 'sentry/icons'; import {tn} from 'sentry/locale'; import overflowEllipsis from 'sentry/styles/overflowEllipsis'; import space from 'sentry/styles/space'; @@ -8,44 +9,46 @@ import {OrganizationSummary} from 'sentry/types'; type Props = { organization: OrganizationSummary; + className?: string; /** * Show the project count under the organization name. */ projectCount?: number; }; -const SidebarOrgSummary = ({organization, projectCount}: Props) => ( - <OrgSummary> - <OrganizationAvatar organization={organization} size={36} /> - <Details> - <Name>{organization.name}</Name> - {!!projectCount && <Extra>{tn('%s project', '%s projects', projectCount)}</Extra>} - </Details> - </OrgSummary> -); - -const OrgSummary = styled('div')` +const SidebarOrgSummary = styled(({organization, projectCount, ...props}: Props) => ( + <div {...props}> + {organization.status.id === 'pending_deletion' ? ( + <PendingDeletionAvatar data-test-id="pending-deletion-icon" /> + ) : ( + <OrganizationAvatar organization={organization} size={36} /> + )} + <div> + <Name pendingDeletion={organization.status.id === 'pending_deletion'}> + {organization.name} + </Name> + {!!projectCount && ( + <ProjectCount>{tn('%s project', '%s projects', projectCount)}</ProjectCount> + )} + </div> + </div> +))` display: grid; - grid-template-columns: max-content 1fr; + grid-template-columns: max-content minmax(0, 1fr); gap: ${space(1)}; align-items: center; padding: ${space(1)} ${p => p.theme.sidebar.menuSpacing}; - overflow: hidden; `; -const Details = styled('div')` - overflow: hidden; -`; - -const Name = styled('div')` - color: ${p => p.theme.textColor}; +const Name = styled('div')<{pendingDeletion: boolean}>` + color: ${p => (p.pendingDeletion ? p.theme.subText : p.theme.textColor)}; font-size: ${p => p.theme.fontSizeLarge}; line-height: 1.1; font-weight: bold; ${overflowEllipsis}; `; -const Extra = styled('div')` +const ProjectCount = styled('div')` color: ${p => p.theme.subText}; font-size: ${p => p.theme.fontSizeMedium}; line-height: 1; @@ -53,7 +56,18 @@ const Extra = styled('div')` ${overflowEllipsis}; `; -// Needed for styling in SidebarMenuItem -export {OrgSummary}; +const PendingDeletionAvatar = styled('div')` + height: 36px; + width: 36px; + display: flex; + align-items: center; + justify-content: center; + border: 2px dashed ${p => p.theme.gray200}; + border-radius: 4px; +`; + +PendingDeletionAvatar.defaultProps = { + children: <IconWarning size="sm" color="gray200" />, +}; export default SidebarOrgSummary; diff --git a/tests/js/spec/components/sidebar/switchOrganization.spec.jsx b/tests/js/spec/components/sidebar/switchOrganization.spec.jsx deleted file mode 100644 index f9bbbb0a7cb09a..00000000000000 --- a/tests/js/spec/components/sidebar/switchOrganization.spec.jsx +++ /dev/null @@ -1,57 +0,0 @@ -import {mountWithTheme} from 'sentry-test/enzyme'; - -import {SwitchOrganization} from 'sentry/components/sidebar/sidebarDropdown/switchOrganization'; - -describe('SwitchOrganization', function () { - it('can list organizations', function () { - jest.useFakeTimers(); - const wrapper = mountWithTheme( - <SwitchOrganization - organizations={[TestStubs.Organization(), TestStubs.Organization({slug: 'org2'})]} - /> - ); - - wrapper.find('SwitchOrganizationMenuActor').simulate('mouseEnter'); - jest.advanceTimersByTime(500); - wrapper.update(); - expect(wrapper.find('OrganizationList')).toHaveLength(1); - expect(wrapper.find('OrganizationList SidebarMenuItem')).toHaveLength(2); - jest.useRealTimers(); - }); - - it('shows "Create an Org" if they have permission', function () { - jest.useFakeTimers(); - const wrapper = mountWithTheme( - <SwitchOrganization - organizations={[TestStubs.Organization(), TestStubs.Organization({slug: 'org2'})]} - canCreateOrganization - /> - ); - - wrapper.find('SwitchOrganizationMenuActor').simulate('mouseEnter'); - jest.advanceTimersByTime(500); - wrapper.update(); - expect( - wrapper.find('SidebarMenuItem[data-test-id="sidebar-create-org"]') - ).toHaveLength(1); - jest.useRealTimers(); - }); - - it('does not have "Create an Org" if they do not have permission', function () { - jest.useFakeTimers(); - const wrapper = mountWithTheme( - <SwitchOrganization - organizations={[TestStubs.Organization(), TestStubs.Organization({slug: 'org2'})]} - canCreateOrganization={false} - /> - ); - - wrapper.find('SwitchOrganizationMenuActor').simulate('mouseEnter'); - jest.advanceTimersByTime(500); - wrapper.update(); - expect( - wrapper.find('SidebarMenuItem[data-test-id="sidebar-create-org"]') - ).toHaveLength(0); - jest.useRealTimers(); - }); -}); diff --git a/tests/js/spec/components/sidebar/switchOrganization.spec.tsx b/tests/js/spec/components/sidebar/switchOrganization.spec.tsx new file mode 100644 index 00000000000000..208a10c3d48a2f --- /dev/null +++ b/tests/js/spec/components/sidebar/switchOrganization.spec.tsx @@ -0,0 +1,70 @@ +import {act, render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; + +import {SwitchOrganization} from 'sentry/components/sidebar/sidebarDropdown/switchOrganization'; + +describe('SwitchOrganization', function () { + it('can list organizations', async function () { + jest.useFakeTimers(); + render( + <SwitchOrganization + canCreateOrganization={false} + organizations={[ + TestStubs.Organization({name: 'Organization 1'}), + TestStubs.Organization({name: 'Organization 2', slug: 'org2'}), + ]} + /> + ); + + userEvent.hover(screen.getByTestId('sidebar-switch-org')); + act(() => void jest.advanceTimersByTime(500)); + + expect(screen.getByRole('list')).toBeInTheDocument(); + + expect(screen.getByText('Organization 1')).toBeInTheDocument(); + expect(screen.getByText('Organization 2')).toBeInTheDocument(); + jest.useRealTimers(); + }); + + it('shows "Create an Org" if they have permission', function () { + jest.useFakeTimers(); + render(<SwitchOrganization canCreateOrganization organizations={[]} />); + + userEvent.hover(screen.getByTestId('sidebar-switch-org')); + act(() => void jest.advanceTimersByTime(500)); + + expect(screen.getByTestId('sidebar-create-org')).toBeInTheDocument(); + jest.useRealTimers(); + }); + + it('does not have "Create an Org" if they do not have permission', function () { + jest.useFakeTimers(); + render(<SwitchOrganization canCreateOrganization={false} organizations={[]} />); + + userEvent.hover(screen.getByTestId('sidebar-switch-org')); + act(() => void jest.advanceTimersByTime(500)); + + expect(screen.queryByTestId('sidebar-create-org')).not.toBeInTheDocument(); + jest.useRealTimers(); + }); + + it('shows orgs pending deletion with a special icon', function () { + const orgPendingDeletion = TestStubs.Organization({ + slug: 'org-2', + status: {id: 'pending_deletion', name: 'pending_deletion'}, + }); + + jest.useFakeTimers(); + render( + <SwitchOrganization + canCreateOrganization + organizations={[TestStubs.Organization(), orgPendingDeletion]} + /> + ); + + userEvent.hover(screen.getByTestId('sidebar-switch-org')); + act(() => void jest.advanceTimersByTime(500)); + + expect(screen.getByTestId('pending-deletion-icon')).toBeInTheDocument(); + jest.useRealTimers(); + }); +});
8303f18ccf541186c3759132ea936cdcf1e55f91
2023-01-05 23:04:40
Jonas
fix(flamechart): prevent browser nav (#42815)
false
prevent browser nav (#42815)
fix
diff --git a/static/app/components/profiling/flamegraph/interactions/useCanvasZoomOrScroll.tsx b/static/app/components/profiling/flamegraph/interactions/useCanvasZoomOrScroll.tsx index 5a9789b2a44efc..b70a87c3b41221 100644 --- a/static/app/components/profiling/flamegraph/interactions/useCanvasZoomOrScroll.tsx +++ b/static/app/components/profiling/flamegraph/interactions/useCanvasZoomOrScroll.tsx @@ -36,6 +36,9 @@ export function useCanvasZoomOrScroll({ setLastInteraction(null); }, 300); + // We need to prevent the default behavior of the wheel event or we + // risk triggering back/forward browser navigation + evt.preventDefault(); // When we zoom, we want to clear cursor so that any tooltips // rendered on the flamegraph are removed from the flamegraphView setConfigSpaceCursor(null); @@ -50,14 +53,13 @@ export function useCanvasZoomOrScroll({ } } - const options: AddEventListenerOptions & EventListenerOptions = {passive: true}; - canvas.addEventListener('wheel', onCanvasWheel, options); + canvas.addEventListener('wheel', onCanvasWheel); return () => { if (wheelStopTimeoutId.current !== undefined) { window.cancelAnimationFrame(wheelStopTimeoutId.current); } - canvas.removeEventListener('wheel', onCanvasWheel, options); + canvas.removeEventListener('wheel', onCanvasWheel); }; }, [ canvas,
092afb445bab0b72213a9097394db8d859c5be0f
2024-04-18 22:25:46
Evan Purkhiser
feat(crons): Add backend owner filtering (#69135)
false
Add backend owner filtering (#69135)
feat
diff --git a/src/sentry/apidocs/parameters.py b/src/sentry/apidocs/parameters.py index cc9557060248e0..6a2da617291b01 100644 --- a/src/sentry/apidocs/parameters.py +++ b/src/sentry/apidocs/parameters.py @@ -217,6 +217,13 @@ class MonitorParams: type=str, description="The name of environment for the monitor environment.", ) + OWNER = OpenApiParameter( + name="owner", + location="query", + required=False, + type=str, + description="The owner of the monitor, in the format `user:id` or `team:id`. May be specified multiple times.", + ) class EventParams: diff --git a/src/sentry/monitors/endpoints/organization_monitor_index.py b/src/sentry/monitors/endpoints/organization_monitor_index.py index 9bc0a6129f0e43..8e4c615d9aee18 100644 --- a/src/sentry/monitors/endpoints/organization_monitor_index.py +++ b/src/sentry/monitors/endpoints/organization_monitor_index.py @@ -18,6 +18,7 @@ from sentry.api.base import region_silo_endpoint from sentry.api.bases import NoProjects from sentry.api.bases.organization import OrganizationEndpoint +from sentry.api.helpers.teams import get_teams from sentry.api.paginator import OffsetPaginator from sentry.api.serializers import serialize from sentry.apidocs.constants import ( @@ -26,7 +27,7 @@ RESPONSE_NOT_FOUND, RESPONSE_UNAUTHORIZED, ) -from sentry.apidocs.parameters import GlobalParams, OrganizationParams +from sentry.apidocs.parameters import GlobalParams, MonitorParams, OrganizationParams from sentry.apidocs.utils import inline_sentry_response_serializer from sentry.constants import ObjectStatus from sentry.db.models.query import in_iexact @@ -49,6 +50,7 @@ from sentry.monitors.utils import create_issue_alert_rule, signal_monitor_created from sentry.monitors.validators import MonitorBulkEditValidator, MonitorValidator from sentry.search.utils import tokenize_query +from sentry.utils.actor import ActorTuple from sentry.utils.outcomes import Outcome from .base import OrganizationMonitorPermission @@ -105,6 +107,7 @@ class OrganizationMonitorIndexEndpoint(OrganizationEndpoint): GlobalParams.ORG_SLUG, OrganizationParams.PROJECT, GlobalParams.ENVIRONMENT, + MonitorParams.OWNER, ], responses={ 200: inline_sentry_response_serializer("MonitorList", list[MonitorSerializerResponse]), @@ -131,6 +134,7 @@ def get(self, request: Request, organization: Organization) -> Response: ] ) query = request.GET.get("query") + owners = request.GET.getlist("owner") is_asc = request.GET.get("asc", "1") == "1" sort = request.GET.get("sort", "status") @@ -196,6 +200,29 @@ def get(self, request: Request, organization: Organization) -> Response: if not is_asc: sort_fields = [flip_sort_direction(sort_field) for sort_field in sort_fields] + 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 [] + owners.discard("myteams") + + actors = [ActorTuple.from_actor_identifier(identifier) for identifier in owners] + + user_ids = [actor.id for actor in actors if actor.type == User] + team_ids = [actor.id for actor in actors if actor.type == Team] + + teams = get_teams( + request, + organization, + teams=[*team_ids, *myteams], + ) + 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) + ) + if query: tokens = tokenize_query(query) for key, value in tokens.items(): diff --git a/tests/sentry/monitors/endpoints/test_organization_monitor_index.py b/tests/sentry/monitors/endpoints/test_organization_monitor_index.py index ea4f339fb76cdf..8c1bc586168cbb 100644 --- a/tests/sentry/monitors/endpoints/test_organization_monitor_index.py +++ b/tests/sentry/monitors/endpoints/test_organization_monitor_index.py @@ -209,6 +209,43 @@ def test_sort_muted_envs(self): ) self.check_valid_response(response, expected) + def test_filter_owners(self): + user_1 = self.create_user() + user_2 = self.create_user() + team_1 = self.create_team() + 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) + + # Monitor by user + response = self.get_success_response(self.organization.slug, owner=[f"user:{user_1.id}"]) + self.check_valid_response(response, [mon_1]) + + # 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]) + + # myteams + response = self.get_success_response( + self.organization.slug, + owner=["myteams"], + ) + self.check_valid_response(response, [mon_4]) + + # Invalid user ID + response = self.get_success_response( + self.organization.slug, + owner=["user:12345"], + ) + self.check_valid_response(response, []) + def test_all_monitor_environments(self): monitor = self._create_monitor() monitor_environment = self._create_monitor_environment(
24148fcfe0dc7033c59bf28f574203dd4250ae37
2023-09-22 05:15:30
Seiji Chew
docs(api): Sort path+body+body params by required (#56639)
false
Sort path+body+body params by required (#56639)
docs
diff --git a/src/sentry/apidocs/hooks.py b/src/sentry/apidocs/hooks.py index 45a73bdab0fb13..58e21485274039 100644 --- a/src/sentry/apidocs/hooks.py +++ b/src/sentry/apidocs/hooks.py @@ -1,5 +1,6 @@ import json # noqa: S003 import os +from collections import OrderedDict from typing import Any, Dict, List, Literal, Mapping, Set, Tuple, TypedDict from sentry.api.api_owners import ApiOwner @@ -197,18 +198,44 @@ def custom_postprocessing_hook(result: Any, generator: Any, **kwargs: Any) -> An for path, endpoints in result["paths"].items(): for method_info in endpoints.values(): _check_tag(path, method_info) + endpoint_name = f"'{method_info['operationId']}'" if method_info.get("description") is None: raise SentryApiBuildError( - "Please add a description to your endpoint method via a docstring" + f"Please add a description via docstring to your endpoint {endpoint_name}" ) - # ensure path parameters have a description + for param in method_info.get("parameters", []): + # Ensure path parameters have a description if param["in"] == "path" and param.get("description") is None: raise SentryApiBuildError( - f"Please add a description to your path parameter '{param['name']}'" + f"Please add a description to your path parameter '{param['name']}' for endpoint {endpoint_name}" ) + # Ensure body parameters are sorted by placing required parameters first + if "requestBody" in method_info: + try: + content = method_info["requestBody"]["content"] + # media type can either "multipart/form-data" or "application/json" + if "multipart/form-data" in content: + schema = content["multipart/form-data"]["schema"] + else: + schema = content["application/json"]["schema"] + + # Required params are stored in a list and not in the param itself + required = set(schema.get("required", [])) + if required: + # Explicitly sort body params by converting the dict to an ordered dict + schema["properties"] = OrderedDict( + sorted( + schema["properties"].items(), + key=lambda param: 0 if param[0] in required else 1, + ) + ) + except KeyError as e: + raise SentryApiBuildError( + f"Unable to parse body parameters due to KeyError {e} for endpoint {endpoint_name}. Please post in #discuss-apis to fix." + ) return result diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 69a65b7e23f7ec..166a32862c7a52 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1320,6 +1320,17 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str: } +def custom_parameter_sort(parameter: dict) -> tuple[str, int]: + """ + Sort parameters by type then if the parameter is required or not. + It should group path parameters first, then query parameters. + In each group, required parameters should come before optional parameters. + """ + param_type = parameter["in"] + required = parameter.get("required", False) + return (param_type, 0 if required else 1) + + if os.environ.get("OPENAPIGENERATE", False): OLD_OPENAPI_JSON_PATH = "tests/apidocs/openapi-deprecated.json" from sentry.apidocs.build import OPENAPI_TAGS, get_old_json_components, get_old_json_paths @@ -1342,7 +1353,7 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str: "PARSER_WHITELIST": ["rest_framework.parsers.JSONParser"], "APPEND_PATHS": get_old_json_paths(OLD_OPENAPI_JSON_PATH), "APPEND_COMPONENTS": get_old_json_components(OLD_OPENAPI_JSON_PATH), - "SORT_OPERATION_PARAMETERS": False, + "SORT_OPERATION_PARAMETERS": custom_parameter_sort, } CRISPY_TEMPLATE_PACK = "bootstrap3"
e0e5c022db33cb36c957b9fade5a410d24041856
2025-01-15 03:59:02
anthony sottile
ref: fix argument errors in dispatch signatures (#83447)
false
fix argument errors in dispatch signatures (#83447)
ref
diff --git a/.github/workflows/backend.yml b/.github/workflows/backend.yml index f05a26660a1d16..2ec381aa97831c 100644 --- a/.github/workflows/backend.yml +++ b/.github/workflows/backend.yml @@ -330,6 +330,7 @@ jobs: # mypy does not have granular codes so don't allow specific messages to regress set -euo pipefail ! grep "'Settings' object has no attribute" .artifacts/mypy-all + ! grep 'Argument .* of "dispatch" is incompatible with' .artifacts/mypy-all ! grep 'Cannot override class variable' .artifacts/mypy-all ! grep 'Exception type must be derived from BaseException' .artifacts/mypy-all ! grep 'Incompatible default for argument' .artifacts/mypy-all diff --git a/pyproject.toml b/pyproject.toml index 428343df75796d..0f9d4ae442fabb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -183,10 +183,8 @@ module = [ "sentry.incidents.tasks", "sentry.integrations.aws_lambda.integration", "sentry.integrations.bitbucket.client", - "sentry.integrations.bitbucket.installed", "sentry.integrations.bitbucket.integration", "sentry.integrations.bitbucket.issues", - "sentry.integrations.bitbucket.uninstalled", "sentry.integrations.bitbucket_server.client", "sentry.integrations.bitbucket_server.integration", "sentry.integrations.example.integration", diff --git a/src/sentry/api/endpoints/auth_config.py b/src/sentry/api/endpoints/auth_config.py index b1bea79ec01375..41af593f2d2b97 100644 --- a/src/sentry/api/endpoints/auth_config.py +++ b/src/sentry/api/endpoints/auth_config.py @@ -1,5 +1,7 @@ from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME +from django.http.request import HttpRequest +from django.http.response import HttpResponseBase from django.urls import reverse from rest_framework.request import Request from rest_framework.response import Response @@ -30,7 +32,7 @@ class AuthConfigEndpoint(Endpoint, OrganizationMixin): # Disable authentication and permission requirements. permission_classes = () - def dispatch(self, request: Request, *args, **kwargs) -> Response: + def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: self.determine_active_organization(request) return super().dispatch(request, *args, **kwargs) diff --git a/src/sentry/integrations/bitbucket/installed.py b/src/sentry/integrations/bitbucket/installed.py index b80ea0fefd272e..e0436558b30599 100644 --- a/src/sentry/integrations/bitbucket/installed.py +++ b/src/sentry/integrations/bitbucket/installed.py @@ -1,3 +1,5 @@ +from django.http.request import HttpRequest +from django.http.response import HttpResponseBase from django.views.decorators.csrf import csrf_exempt from rest_framework.request import Request from rest_framework.response import Response @@ -20,7 +22,7 @@ class BitbucketInstalledEndpoint(Endpoint): permission_classes = () @csrf_exempt - def dispatch(self, request: Request, *args, **kwargs) -> Response: + def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: return super().dispatch(request, *args, **kwargs) def post(self, request: Request, *args, **kwargs) -> Response: diff --git a/src/sentry/integrations/bitbucket/uninstalled.py b/src/sentry/integrations/bitbucket/uninstalled.py index 6b660b68d9df4e..f46735af5cb3f0 100644 --- a/src/sentry/integrations/bitbucket/uninstalled.py +++ b/src/sentry/integrations/bitbucket/uninstalled.py @@ -1,3 +1,5 @@ +from django.http.request import HttpRequest +from django.http.response import HttpResponseBase from django.views.decorators.csrf import csrf_exempt from rest_framework.request import Request from rest_framework.response import Response @@ -25,7 +27,7 @@ class BitbucketUninstalledEndpoint(Endpoint): permission_classes = () @csrf_exempt - def dispatch(self, request: Request, *args, **kwargs) -> Response: + def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: return super().dispatch(request, *args, **kwargs) def post(self, request: Request, *args, **kwargs) -> Response: diff --git a/src/sentry/integrations/jira/webhooks/base.py b/src/sentry/integrations/jira/webhooks/base.py index 2df7f73b877169..61a8403982cb0c 100644 --- a/src/sentry/integrations/jira/webhooks/base.py +++ b/src/sentry/integrations/jira/webhooks/base.py @@ -5,6 +5,8 @@ from collections.abc import MutableMapping from typing import Any +from django.http.request import HttpRequest +from django.http.response import HttpResponseBase from django.views.decorators.csrf import csrf_exempt from psycopg2 import OperationalError from rest_framework import status @@ -34,7 +36,7 @@ class JiraWebhookBase(Endpoint, abc.ABC): provider = "jira" @csrf_exempt - def dispatch(self, request: Request, *args, **kwargs) -> Response: + def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: return super().dispatch(request, *args, **kwargs) def handle_exception_with_details( diff --git a/src/sentry/integrations/vercel/webhook.py b/src/sentry/integrations/vercel/webhook.py index af9db32bcce275..c47bf3282a4087 100644 --- a/src/sentry/integrations/vercel/webhook.py +++ b/src/sentry/integrations/vercel/webhook.py @@ -6,6 +6,8 @@ from collections.abc import Mapping from typing import Any +from django.http.request import HttpRequest +from django.http.response import HttpResponseBase from django.utils.crypto import constant_time_compare from django.views.decorators.csrf import csrf_exempt from requests.exceptions import RequestException @@ -139,7 +141,7 @@ class VercelWebhookEndpoint(Endpoint): provider = "vercel" @csrf_exempt - def dispatch(self, request: Request, *args, **kwargs) -> Response: + def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponseBase: return super().dispatch(request, *args, **kwargs) def parse_external_id(self, request: Request) -> str:
0bbbb4e5d3416a270006692dc5d782c5b9513c60
2022-05-18 00:14:58
Evan Purkhiser
ref(tooltip): Rename popperStyle -> overlayStyle (#34687)
false
Rename popperStyle -> overlayStyle (#34687)
ref
diff --git a/static/app/components/createAlertButton.tsx b/static/app/components/createAlertButton.tsx index b13f08da308832..3686339011ecd9 100644 --- a/static/app/components/createAlertButton.tsx +++ b/static/app/components/createAlertButton.tsx @@ -426,7 +426,7 @@ const CreateAlertButton = withRouter( tooltipProps={{ isHoverable: true, position: 'top', - popperStyle: { + overlayStyle: { maxWidth: '270px', }, }} diff --git a/static/app/components/questionTooltip.tsx b/static/app/components/questionTooltip.tsx index 4b2597ee4d8639..99c4f7d724a666 100644 --- a/static/app/components/questionTooltip.tsx +++ b/static/app/components/questionTooltip.tsx @@ -33,7 +33,7 @@ type QuestionProps = { Partial< Pick< React.ComponentProps<typeof Tooltip>, - 'containerDisplayMode' | 'isHoverable' | 'popperStyle' + 'containerDisplayMode' | 'isHoverable' | 'overlayStyle' > >; diff --git a/static/app/components/searchSyntax/renderer.tsx b/static/app/components/searchSyntax/renderer.tsx index 2125bdb0f0be31..1710beec58aab0 100644 --- a/static/app/components/searchSyntax/renderer.tsx +++ b/static/app/components/searchSyntax/renderer.tsx @@ -130,7 +130,7 @@ const FilterToken = ({ <Tooltip disabled={!showTooltip} title={filter.invalid?.reason} - popperStyle={{maxWidth: '350px'}} + overlayStyle={{maxWidth: '350px'}} forceVisible skipWrapper > diff --git a/static/app/components/tooltip.tsx b/static/app/components/tooltip.tsx index 72a7c1536c21f8..3a36bd40cd2388 100644 --- a/static/app/components/tooltip.tsx +++ b/static/app/components/tooltip.tsx @@ -85,7 +85,7 @@ export interface InternalTooltipProps { /** * Additional style rules for the tooltip content. */ - popperStyle?: React.CSSProperties | SerializedStyles; + overlayStyle?: React.CSSProperties | SerializedStyles; /** * Position for the tooltip. @@ -148,7 +148,7 @@ export function DO_NOT_USE_TOOLTIP({ delay, forceVisible, isHoverable, - popperStyle, + overlayStyle, showUnderline, underlineColor, showOnlyOnOverflow, @@ -291,7 +291,7 @@ export function DO_NOT_USE_TOOLTIP({ id={tooltipId} data-placement={placement} style={computeOriginFromArrow(position, arrowProps)} - popperStyle={popperStyle} + overlayStyle={overlayStyle} onMouseEnter={isHoverable ? handleMouseEnter : undefined} onMouseLeave={isHoverable ? handleMouseLeave : undefined} {...TOOLTIP_ANIMATION} @@ -335,7 +335,7 @@ const TooltipContent = styled(motion.div, { shouldForwardProp: (prop: string) => typeof prop === 'string' && (animationProps.includes(prop) || isPropValid(prop)), })<{ - popperStyle: InternalTooltipProps['popperStyle']; + overlayStyle: InternalTooltipProps['overlayStyle']; }>` will-change: transform, opacity; position: relative; @@ -352,7 +352,7 @@ const TooltipContent = styled(motion.div, { margin: 6px; text-align: center; - ${p => p.popperStyle as any}; + ${p => p.overlayStyle as any}; `; const TooltipArrow = styled('span')` diff --git a/static/app/components/version.tsx b/static/app/components/version.tsx index 00cb7290b0158f..b19da7ed5a1848 100644 --- a/static/app/components/version.tsx +++ b/static/app/components/version.tsx @@ -122,8 +122,9 @@ const Version = ({ </TooltipContent> ); - const getPopperStyles = () => { - // if the version name is not a hash (sha1 or sha265) and we are not on mobile, allow tooltip to be as wide as 500px + const getOverlayStyle = () => { + // if the version name is not a hash (sha1 or sha265) and we are not on + // mobile, allow tooltip to be as wide as 500px if (/(^[a-f0-9]{40}$)|(^[a-f0-9]{64}$)/.test(version)) { return undefined; } @@ -141,7 +142,7 @@ const Version = ({ disabled={!tooltipRawVersion} isHoverable containerDisplayMode={truncate ? 'block' : 'inline-block'} - popperStyle={getPopperStyles()} + overlayStyle={getOverlayStyle()} > {renderVersion()} </Tooltip> diff --git a/static/app/utils/dashboards/issueFieldRenderers.tsx b/static/app/utils/dashboards/issueFieldRenderers.tsx index 288c55dd295dfa..0f4b9df42f05db 100644 --- a/static/app/utils/dashboards/issueFieldRenderers.tsx +++ b/static/app/utils/dashboards/issueFieldRenderers.tsx @@ -166,7 +166,7 @@ const issuesCountRenderer = ( <Tooltip isHoverable skipWrapper - popperStyle={{padding: 0}} + overlayStyle={{padding: 0}} title={ <div> {filteredCount ? ( diff --git a/static/app/views/settings/project/filtersAndSampling/modal/transactionRuleModal.tsx b/static/app/views/settings/project/filtersAndSampling/modal/transactionRuleModal.tsx index 9f27ac6656017b..13179d35590f18 100644 --- a/static/app/views/settings/project/filtersAndSampling/modal/transactionRuleModal.tsx +++ b/static/app/views/settings/project/filtersAndSampling/modal/transactionRuleModal.tsx @@ -147,7 +147,7 @@ function TransactionRuleModal({rule, errorRules, transactionRules, ...props}: Pr <Tooltip title={t('This field can only be edited if there are no match conditions')} disabled={!isTracingDisabled} - popperStyle={css` + overlayStyle={css` @media (min-width: ${theme.breakpoints[0]}) { max-width: 370px; }
fc654452156e9356751bafb79999786cd109153c
2023-09-12 16:43:04
Ogi
feat(alerts): on demand support for apdex (#56000)
false
on demand support for apdex (#56000)
feat
diff --git a/static/app/components/alerts/onDemandMetricAlert.tsx b/static/app/components/alerts/onDemandMetricAlert.tsx index cef4cd5e7ef56b..3a401c385f66d0 100644 --- a/static/app/components/alerts/onDemandMetricAlert.tsx +++ b/static/app/components/alerts/onDemandMetricAlert.tsx @@ -47,7 +47,7 @@ export function OnDemandMetricAlert({ }) { const {dismiss, isDismissed} = useDismissAlert({key: LOCAL_STORAGE_KEY}); - if (isDismissed) { + if (dismissable && isDismissed) { return null; } diff --git a/static/app/utils/onDemandMetrics/index.tsx b/static/app/utils/onDemandMetrics/index.tsx index 2d1e6292152151..87bb8b37bc723e 100644 --- a/static/app/utils/onDemandMetrics/index.tsx +++ b/static/app/utils/onDemandMetrics/index.tsx @@ -7,7 +7,7 @@ import { TokenResult, } from 'sentry/components/searchSyntax/parser'; import {Organization} from 'sentry/types'; -import {FieldKey, getFieldDefinition} from 'sentry/utils/fields'; +import {AggregationKey, FieldKey, getFieldDefinition} from 'sentry/utils/fields'; import { ON_DEMAND_METRICS_UNSUPPORTED_TAGS, STANDARD_SEARCH_FIELD_KEYS, @@ -38,6 +38,10 @@ export function createOnDemandFilterWarning(warning: React.ReactNode) { }; } +export function isOnDemandAggregate(aggregate: string): boolean { + return aggregate.includes(AggregationKey.APDEX); +} + export function isOnDemandQueryString(query: string): boolean { const searchFilterKeys = getSearchFilterKeys(query); const isStandardSearch = searchFilterKeys.every(isStandardSearchFilterKey); diff --git a/static/app/views/alerts/rules/metric/details/body.tsx b/static/app/views/alerts/rules/metric/details/body.tsx index 6cedff542033dd..600a240413d90b 100644 --- a/static/app/views/alerts/rules/metric/details/body.tsx +++ b/static/app/views/alerts/rules/metric/details/body.tsx @@ -128,7 +128,7 @@ export default function MetricDetailsBody({ ); } - const {query, dataset} = rule; + const {dataset, aggregate, query} = rule; const queryWithTypeFilter = `${query} ${extractEventTypeFilterFromRule(rule)}`.trim(); const relativeOptions = { @@ -139,7 +139,7 @@ export default function MetricDetailsBody({ const isSnoozed = rule.snooze; const ruleActionCategory = getAlertRuleActionCategory(rule); - const isOnDemandAlert = isOnDemandMetricAlert(dataset, query); + const isOnDemandAlert = isOnDemandMetricAlert(dataset, aggregate, query); return ( <Fragment> @@ -225,10 +225,7 @@ export default function MetricDetailsBody({ </DetailWrapper> </Layout.Main> <Layout.Side> - <MetricDetailsSidebar - rule={rule} - isOnDemandMetricAlert={isOnDemandMetricAlert(dataset, query)} - /> + <MetricDetailsSidebar rule={rule} isOnDemandMetricAlert={isOnDemandAlert} /> </Layout.Side> </Layout.Body> </Fragment> diff --git a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx index b485c22b2cfa69..b39321b2f40eab 100644 --- a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx +++ b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx @@ -510,7 +510,7 @@ class RuleConditionsForm extends PureComponent<Props, State> { }} hasRecentSearches={dataset !== Dataset.SESSIONS} /> - {isExtrapolatedChartData && ( + {isExtrapolatedChartData && isOnDemandQueryString(value) && ( <OnDemandWarningIcon color="gray500" msg={tct( diff --git a/static/app/views/alerts/rules/metric/ruleForm.tsx b/static/app/views/alerts/rules/metric/ruleForm.tsx index 5dabb42b64f99e..443f51a5a1ac54 100644 --- a/static/app/views/alerts/rules/metric/ruleForm.tsx +++ b/static/app/views/alerts/rules/metric/ruleForm.tsx @@ -790,7 +790,9 @@ class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> { const {isExtrapolatedData} = data ?? {}; this.setState({isExtrapolatedChartData: Boolean(isExtrapolatedData)}); - if (!isOnDemandMetricAlert(this.state.dataset, this.state.query)) { + + const {dataset, aggregate, query} = this.state; + if (!isOnDemandMetricAlert(dataset, aggregate, query)) { this.handleMEPAlertDataset(data); } }; @@ -832,8 +834,6 @@ class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> { location, } = this.state; - const onDemandMetricsAlert = isOnDemandMetricAlert(dataset, query); - const chartProps = { organization, projects: [project], @@ -850,7 +850,7 @@ class RuleFormContainer extends DeprecatedAsyncComponent<Props, State> { comparisonDelta, comparisonType, isQueryValid, - isOnDemandMetricAlert: onDemandMetricsAlert, + isOnDemandMetricAlert: isOnDemandMetricAlert(dataset, aggregate, query), onDataLoaded: this.handleTimeSeriesDataFetched, }; diff --git a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.spec.tsx b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.spec.tsx index e30210ffac7008..7cb69aadff156d 100644 --- a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.spec.tsx +++ b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.spec.tsx @@ -5,23 +5,37 @@ describe('isOnDemandMetricAlert', () => { it('should return true for an alert that contains non standard fields', () => { const dataset = Dataset.GENERIC_METRICS; - expect(isOnDemandMetricAlert(dataset, 'transaction.duration:>1')).toBeTruthy(); - expect(isOnDemandMetricAlert(dataset, 'device.name:foo')).toBeTruthy(); - expect(isOnDemandMetricAlert(dataset, 'geo.region:>US')).toBeTruthy(); + expect( + isOnDemandMetricAlert(dataset, 'count()', 'transaction.duration:>1') + ).toBeTruthy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'device.name:foo')).toBeTruthy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'geo.region:>US')).toBeTruthy(); }); it('should return false for an alert that has only standard fields', () => { const dataset = Dataset.GENERIC_METRICS; - expect(isOnDemandMetricAlert(dataset, 'release:1.0')).toBeFalsy(); - expect(isOnDemandMetricAlert(dataset, 'browser.name:chrome')).toBeFalsy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'release:1.0')).toBeFalsy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'browser.name:chrome')).toBeFalsy(); }); it('should return false if dataset is not generic_metrics', () => { const dataset = Dataset.TRANSACTIONS; - expect(isOnDemandMetricAlert(dataset, 'transaction.duration:>1')).toBeFalsy(); - expect(isOnDemandMetricAlert(dataset, 'device.name:foo')).toBeFalsy(); - expect(isOnDemandMetricAlert(dataset, 'geo.region:>US')).toBeFalsy(); + expect( + isOnDemandMetricAlert(dataset, 'count()', 'transaction.duration:>1') + ).toBeFalsy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'device.name:foo')).toBeFalsy(); + expect(isOnDemandMetricAlert(dataset, 'count()', 'geo.region:>US')).toBeFalsy(); + }); + + it('should return true if aggregate is apdex', () => { + const dataset = Dataset.GENERIC_METRICS; + + expect(isOnDemandMetricAlert(dataset, 'apdex(300)', '')).toBeTruthy(); + expect( + isOnDemandMetricAlert(dataset, 'apdex(300)', 'transaction.duration:>1') + ).toBeTruthy(); + expect(isOnDemandMetricAlert(dataset, 'apdex(300)', 'device.name:foo')).toBeTruthy(); }); }); diff --git a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx index fa6cc7b859e1c7..c38e2fd97068f4 100644 --- a/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx +++ b/static/app/views/alerts/rules/metric/utils/onDemandMetricAlert.tsx @@ -1,5 +1,5 @@ import {AggregationKey} from 'sentry/utils/fields'; -import {isOnDemandQueryString} from 'sentry/utils/onDemandMetrics'; +import {isOnDemandAggregate, isOnDemandQueryString} from 'sentry/utils/onDemandMetrics'; import {Dataset} from 'sentry/views/alerts/rules/metric/types'; export function isValidOnDemandMetricAlert( @@ -7,7 +7,7 @@ export function isValidOnDemandMetricAlert( aggregate: string, query: string ): boolean { - if (!isOnDemandMetricAlert(dataset, query)) { + if (!isOnDemandMetricAlert(dataset, aggregate, query)) { return true; } @@ -19,6 +19,13 @@ export function isValidOnDemandMetricAlert( * We determine that an alert is an on-demand metric alert if the query contains * one of the tags that are not supported by the standard metrics. */ -export function isOnDemandMetricAlert(dataset: Dataset, query: string): boolean { +export function isOnDemandMetricAlert( + dataset: Dataset, + aggregate: string, + query: string +): boolean { + if (isOnDemandAggregate(aggregate)) { + return true; + } return dataset === Dataset.GENERIC_METRICS && isOnDemandQueryString(query); }
63e281302251bd9763573f2b7665ba1647c1682f
2020-03-24 22:07:48
Billy Vong
feat(workflow): Add analytics for Alert views (#17775)
false
Add analytics for Alert views (#17775)
feat
diff --git a/src/sentry/static/sentry/app/views/alerts/details/index.tsx b/src/sentry/static/sentry/app/views/alerts/details/index.tsx index 9d70a24441eda5..b0b968cbbb4bf5 100644 --- a/src/sentry/static/sentry/app/views/alerts/details/index.tsx +++ b/src/sentry/static/sentry/app/views/alerts/details/index.tsx @@ -1,20 +1,24 @@ -import React from 'react'; import {RouteComponentProps} from 'react-router/lib/Router'; +import React from 'react'; import {Client} from 'app/api'; +import {Organization} from 'app/types'; import {addErrorMessage} from 'app/actionCreators/indicator'; import {fetchOrgMembers} from 'app/actionCreators/members'; import {markIncidentAsSeen} from 'app/actionCreators/incident'; import {t} from 'app/locale'; +import {trackAnalyticsEvent} from 'app/utils/analytics'; import withApi from 'app/utils/withApi'; +import withOrganization from 'app/utils/withOrganization'; +import {IncidentStatus, Incident} from '../types'; import {fetchIncident, updateSubscription, updateStatus, isOpen} from '../utils'; import DetailsBody from './body'; import DetailsHeader from './header'; -import {IncidentStatus, Incident} from '../types'; type Props = { api: Client; + organization: Organization; } & RouteComponentProps<{alertId: string; orgId: string}, {}>; type State = { @@ -27,8 +31,17 @@ class IncidentDetails extends React.Component<Props, State> { state: State = {isLoading: false, hasError: false}; componentDidMount() { - const {api, params} = this.props; + const {api, organization, params} = this.props; + + trackAnalyticsEvent({ + eventKey: 'alert_details.viewed', + eventName: 'Alert Details: Viewed', + organization_id: parseInt(organization.id, 10), + alert_id: parseInt(params.alertId, 10), + }); + fetchOrgMembers(api, params.orgId); + this.fetchData(); } @@ -129,4 +142,4 @@ class IncidentDetails extends React.Component<Props, State> { } } -export default withApi(IncidentDetails); +export default withApi(withOrganization(IncidentDetails)); diff --git a/src/sentry/static/sentry/app/views/alerts/list/index.tsx b/src/sentry/static/sentry/app/views/alerts/list/index.tsx index 77af08b7f17ddd..772276a1508804 100644 --- a/src/sentry/static/sentry/app/views/alerts/list/index.tsx +++ b/src/sentry/static/sentry/app/views/alerts/list/index.tsx @@ -8,10 +8,12 @@ import omit from 'lodash/omit'; import styled from '@emotion/styled'; import {IconAdd, IconSettings} from 'app/icons'; +import {Organization} from 'app/types'; import {PageContent, PageHeader} from 'app/styles/organization'; import {Panel, PanelBody, PanelHeader, PanelItem} from 'app/components/panels'; import {navigateTo} from 'app/actionCreators/navigation'; import {t} from 'app/locale'; +import {trackAnalyticsEvent} from 'app/utils/analytics'; import Alert from 'app/components/alert'; import AsyncComponent from 'app/components/asyncComponent'; import BetaTag from 'app/components/betaTag'; @@ -30,6 +32,7 @@ import Projects from 'app/utils/projects'; import getDynamicText from 'app/utils/getDynamicText'; import overflowEllipsis from 'app/styles/overflowEllipsis'; import space from 'app/styles/space'; +import withOrganization from 'app/utils/withOrganization'; import {Incident} from '../types'; import SparkLine from './sparkLine'; @@ -37,7 +40,9 @@ import Status from '../status'; const DEFAULT_QUERY_STATUS = 'open'; -type Props = RouteComponentProps<{orgId: string}, {}>; +type Props = { + organization: Organization; +} & RouteComponentProps<{orgId: string}, {}>; type State = { incidentList: Incident[]; @@ -169,6 +174,28 @@ class IncidentsList extends AsyncComponent<Props, State & AsyncComponent['state' } class IncidentsListContainer extends React.Component<Props> { + componentDidMount() { + this.trackView(); + } + + componentDidUpdate(nextProps: Props) { + if (nextProps.location.query?.status !== this.props.location.query?.status) { + this.trackView(); + } + } + + trackView() { + const {location, organization} = this.props; + const status = getQueryStatus(location.query.status); + + trackAnalyticsEvent({ + eventKey: 'alert_stream.viewed', + eventName: 'Alert Stream: Viewed', + status, + organization_id: parseInt(organization.id, 10), + }); + } + /** * Incidents list is currently at the organization level, but the link needs to * go down to a specific project scope. @@ -337,4 +364,4 @@ const NumericColumn = styled('div')` text-align: right; `; -export default IncidentsListContainer; +export default withOrganization(IncidentsListContainer); diff --git a/src/sentry/static/sentry/app/views/settings/incidentRules/create.tsx b/src/sentry/static/sentry/app/views/settings/incidentRules/create.tsx index dc843f71096a80..7c63f797cc3d9b 100644 --- a/src/sentry/static/sentry/app/views/settings/incidentRules/create.tsx +++ b/src/sentry/static/sentry/app/views/settings/incidentRules/create.tsx @@ -4,7 +4,6 @@ import React from 'react'; import {Organization, Project} from 'app/types'; import {createDefaultRule} from 'app/views/settings/incidentRules/constants'; import recreateRoute from 'app/utils/recreateRoute'; -import withProject from 'app/utils/withProject'; import RuleForm from './ruleForm'; @@ -42,4 +41,4 @@ class IncidentRulesCreate extends React.Component<Props> { } } -export default withProject(IncidentRulesCreate); +export default IncidentRulesCreate; diff --git a/src/sentry/static/sentry/app/views/settings/projectAlerts/create.tsx b/src/sentry/static/sentry/app/views/settings/projectAlerts/create.tsx index 7ef5c210bf3c9e..116eace05cefa6 100644 --- a/src/sentry/static/sentry/app/views/settings/projectAlerts/create.tsx +++ b/src/sentry/static/sentry/app/views/settings/projectAlerts/create.tsx @@ -1,15 +1,17 @@ import {RouteComponentProps} from 'react-router/lib/Router'; import React from 'react'; -import {Organization} from 'app/types'; +import {Organization, Project} from 'app/types'; import {Panel, PanelBody, PanelHeader} from 'app/components/panels'; import {t} from 'app/locale'; +import {trackAnalyticsEvent} from 'app/utils/analytics'; import IncidentRulesCreate from 'app/views/settings/incidentRules/create'; import IssueEditor from 'app/views/settings/projectAlerts/issueEditor'; import PanelItem from 'app/components/panels/panelItem'; import RadioGroup from 'app/views/settings/components/forms/controls/radioGroup'; import SentryDocumentTitle from 'app/components/sentryDocumentTitle'; import SettingsPageHeader from 'app/views/settings/components/settingsPageHeader'; +import withProject from 'app/utils/withProject'; type RouteParams = { orgId: string; @@ -18,6 +20,7 @@ type RouteParams = { type Props = RouteComponentProps<RouteParams, {}> & { organization: Organization; + project: Project; hasMetricAlerts: boolean; }; @@ -34,6 +37,17 @@ class Create extends React.Component<Props, State> { : null, }; + componentDidMount() { + const {organization, project} = this.props; + + trackAnalyticsEvent({ + eventKey: 'new_alert_rule.viewed', + eventName: 'New Alert Rule: Viewed', + organization_id: parseInt(organization.id, 10), + project_id: parseInt(project.id, 10), + }); + } + handleChangeAlertType = (alertType: string) => { // alertType should be `issue` or `metric` this.setState({ @@ -95,4 +109,4 @@ class Create extends React.Component<Props, State> { } } -export default Create; +export default withProject(Create);
2b5059b85d463191e4e50e68a71e912ee5000f20
2023-08-18 23:57:01
anthony sottile
ref: use class name instead of view func __qualname__ for ratelimit key (#55034)
false
use class name instead of view func __qualname__ for ratelimit key (#55034)
ref
diff --git a/src/sentry/ratelimits/utils.py b/src/sentry/ratelimits/utils.py index f3185be66de8a1..385967184c2740 100644 --- a/src/sentry/ratelimits/utils.py +++ b/src/sentry/ratelimits/utils.py @@ -57,7 +57,7 @@ def get_rate_limit_key( ): return None - view = view_func.__qualname__ + view = view_func.view_class.__name__ http_method = request.method # This avoids touching user session, which means we avoid
270a730cc811f1e9aa39604807009946251b16bd
2020-09-09 01:07:51
Chris Fuller
feat(workflow): Capture Snuba's RateLimitExceeded exception as 429, not 500 (#20614)
false
Capture Snuba's RateLimitExceeded exception as 429, not 500 (#20614)
feat
diff --git a/src/sentry/api/endpoints/group_details.py b/src/sentry/api/endpoints/group_details.py index 529069a1eadc7f..70f09df611707b 100644 --- a/src/sentry/api/endpoints/group_details.py +++ b/src/sentry/api/endpoints/group_details.py @@ -200,6 +200,7 @@ def get(self, request, group): """ try: # TODO(dcramer): handle unauthenticated/public response + from sentry.utils import snuba organization = group.project.organization environments = get_environments(request, organization) @@ -324,6 +325,9 @@ def get(self, request, group): metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 200}) return Response(data) + except snuba.RateLimitExceeded: + metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 429}) + raise except Exception: metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 500}) raise @@ -357,6 +361,8 @@ def put(self, request, group): :auth: required """ try: + from sentry.utils import snuba + discard = request.data.get("discard") # TODO(dcramer): we need to implement assignedTo in the bulk mutation @@ -400,6 +406,9 @@ def put(self, request, group): "group.update.http_response", sample_rate=1.0, tags={"status": e.status_code} ) return Response(e.body, status=e.status_code) + except snuba.RateLimitExceeded: + metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 429}) + raise except Exception: metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 500}) raise @@ -416,6 +425,7 @@ def delete(self, request, group): :auth: required """ try: + from sentry.utils import snuba from sentry.tasks.deletion import delete_groups updated = ( @@ -463,6 +473,9 @@ def delete(self, request, group): ) metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 200}) return Response(status=202) + except snuba.RateLimitExceeded: + metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 429}) + raise except Exception: metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 500}) raise diff --git a/src/sentry/api/helpers/group_index.py b/src/sentry/api/helpers/group_index.py index a4452bd819adbe..4d8442ebceab03 100644 --- a/src/sentry/api/helpers/group_index.py +++ b/src/sentry/api/helpers/group_index.py @@ -428,8 +428,13 @@ def self_subscribe_and_assign_issue(acting_user, group): def track_update_groups(function): def wrapper(request, projects, *args, **kwargs): + from sentry.utils import snuba + try: response = function(request, projects, *args, **kwargs) + except snuba.RateLimitExceeded: + metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 429}) + raise except Exception: metrics.incr("group.update.http_response", sample_rate=1.0, tags={"status": 500}) # Continue raising the error now that we've incr the metric diff --git a/src/sentry/tasks/base.py b/src/sentry/tasks/base.py index fd855abefacf5a..146003b6f59e00 100644 --- a/src/sentry/tasks/base.py +++ b/src/sentry/tasks/base.py @@ -84,6 +84,8 @@ def wrapped(*args, **kwargs): def track_group_async_operation(function): def wrapper(*args, **kwargs): + from sentry.utils import snuba + try: response = function(*args, **kwargs) metrics.incr( @@ -92,6 +94,9 @@ def wrapper(*args, **kwargs): tags={"status": 500 if response is False else 200}, ) return response + except snuba.RateLimitExceeded: + metrics.incr("group.update.async_response", sample_rate=1.0, tags={"status": 429}) + raise except Exception: metrics.incr("group.update.async_response", sample_rate=1.0, tags={"status": 500}) # Continue raising the error now that we've incr the metric
9b4a93109c0a0fd70e0ebd54d8aed0485f9197b0
2021-05-21 03:50:02
Taylan Gocmen
fix(ui): Alert details chart header item alignments (#26150)
false
Alert details chart header item alignments (#26150)
fix
diff --git a/static/app/views/alerts/rules/details/body.tsx b/static/app/views/alerts/rules/details/body.tsx index b010e97951b02e..25c455283d5143 100644 --- a/static/app/views/alerts/rules/details/body.tsx +++ b/static/app/views/alerts/rules/details/body.tsx @@ -165,28 +165,28 @@ export default class DetailsBody extends React.Component<Props> { return ( <React.Fragment> <SidebarGroup> - <SidebarHeading>{t('Metric')}</SidebarHeading> + <Heading>{t('Metric')}</Heading> <RuleText>{this.getMetricText()}</RuleText> </SidebarGroup> <SidebarGroup> - <SidebarHeading>{t('Environment')}</SidebarHeading> + <Heading>{t('Environment')}</Heading> <RuleText>{rule.environment ?? 'All'}</RuleText> </SidebarGroup> <SidebarGroup> - <SidebarHeading>{t('Filters')}</SidebarHeading> + <Heading>{t('Filters')}</Heading> {this.getFilter()} </SidebarGroup> <SidebarGroup> - <SidebarHeading>{t('Conditions')}</SidebarHeading> + <Heading>{t('Conditions')}</Heading> {criticalTrigger && this.renderTrigger(criticalTrigger)} {warningTrigger && this.renderTrigger(warningTrigger)} </SidebarGroup> <SidebarGroup> - <SidebarHeading>{t('Other Details')}</SidebarHeading> + <Heading>{t('Other Details')}</Heading> <KeyValueTable> <Feature features={['organizations:team-alerts-ownership']}> <KeyValueTableRow @@ -233,18 +233,14 @@ export default class DetailsBody extends React.Component<Props> { return ( <StatusContainer> - <div> - <SidebarHeading noMargin>{t('Status')}</SidebarHeading> - <ItemValue> - <AlertBadge status={status} /> - </ItemValue> - </div> - <div> - <SidebarHeading noMargin> - {activeIncident ? t('Last Triggered') : t('Last Resolved')} - </SidebarHeading> - <ItemValue>{activityDate ? <TimeSince date={activityDate} /> : '-'}</ItemValue> - </div> + <HeaderItem> + <Heading noMargin>{t('Current Status')}</Heading> + <Status> + <AlertBadge status={status} hideText /> + {activeIncident ? t('Triggered') : t('Resolved')} + {activityDate ? <TimeSince date={activityDate} /> : '-'} + </Status> + </HeaderItem> </StatusContainer> ); } @@ -307,8 +303,8 @@ export default class DetailsBody extends React.Component<Props> { <Layout.Main> <HeaderContainer> <HeaderGrid> - <div> - <SidebarHeading noMargin>{t('Display')}</SidebarHeading> + <HeaderItem> + <Heading noMargin>{t('Display')}</Heading> <ChartControls> <DropdownControl label={timePeriod.display}> {TIME_OPTIONS.map(({label, value}) => ( @@ -322,16 +318,16 @@ export default class DetailsBody extends React.Component<Props> { ))} </DropdownControl> </ChartControls> - </div> + </HeaderItem> {projects && projects.length && ( - <div> - <SidebarHeading noMargin>{t('Project')}</SidebarHeading> + <HeaderItem> + <Heading noMargin>{t('Project')}</Heading> <IdBadge avatarSize={16} project={projects[0]} /> - </div> + </HeaderItem> )} - <div> - <SidebarHeading noMargin> + <HeaderItem> + <Heading noMargin> {t('Time Interval')} <Tooltip title={t( @@ -340,10 +336,10 @@ export default class DetailsBody extends React.Component<Props> { > <IconInfo size="xs" color="gray200" /> </Tooltip> - </SidebarHeading> + </Heading> <RuleText>{this.getTimeWindow()}</RuleText> - </div> + </HeaderItem> </HeaderGrid> </HeaderContainer> @@ -427,6 +423,7 @@ const StatusWrapper = styled('div')` `; const HeaderContainer = styled('div')` + height: 60px; display: flex; flex-direction: row; align-content: flex-start; @@ -435,8 +432,20 @@ const HeaderContainer = styled('div')` const HeaderGrid = styled('div')` display: grid; grid-template-columns: auto auto auto; - align-items: flex-start; - gap: ${space(4)}; + align-items: stretch; + grid-gap: 60px; +`; + +const HeaderItem = styled('div')` + flex: 1; + display: flex; + flex-direction: column; + + > *:nth-child(2) { + flex: 1; + display: flex; + align-items: center; + } `; const StyledLayoutBody = styled(Layout.Body)` @@ -462,22 +471,21 @@ const ActivityWrapper = styled('div')` width: 100%; `; -const ItemValue = styled('div')` - display: flex; - justify-content: flex-start; - align-items: center; +const Status = styled('div')` position: relative; - font-size: ${p => p.theme.fontSizeExtraLarge}; + display: grid; + grid-template-columns: auto auto auto; + grid-gap: ${space(0.5)}; + font-size: ${p => p.theme.fontSizeLarge}; `; const StatusContainer = styled('div')` - display: grid; - grid-template-columns: 50% 50%; - grid-row-gap: 16px; - margin-bottom: 20px; + height: 60px; + display: flex; + margin-bottom: ${space(1.5)}; `; -const SidebarHeading = styled(SectionHeading)<{noMargin?: boolean}>` +const Heading = styled(SectionHeading)<{noMargin?: boolean}>` display: grid; grid-template-columns: auto auto; justify-content: flex-start; diff --git a/static/app/views/alerts/rules/details/metricChart.tsx b/static/app/views/alerts/rules/details/metricChart.tsx index 37638eebb813de..127b58bf924128 100644 --- a/static/app/views/alerts/rules/details/metricChart.tsx +++ b/static/app/views/alerts/rules/details/metricChart.tsx @@ -15,6 +15,7 @@ import MarkArea from 'app/components/charts/components/markArea'; import MarkLine from 'app/components/charts/components/markLine'; import EventsRequest from 'app/components/charts/eventsRequest'; import LineChart, {LineChartSeries} from 'app/components/charts/lineChart'; +import {SectionHeading} from 'app/components/charts/styles'; import { parseStatsPeriod, StatsPeriodType, @@ -672,10 +673,14 @@ const ChartSummary = styled('div')` margin-right: auto; `; -const SummaryText = styled('span')` - margin-top: ${space(0.25)}; +const SummaryText = styled(SectionHeading)` + flex: 1; + display: flex; + align-items: center; + margin: 0; font-weight: bold; font-size: ${p => p.theme.fontSizeSmall}; + line-height: 1; `; const SummaryStats = styled('div')`
e1b25d625b185588fc7c2834dff5ea5bb3a98ce0
2022-07-30 00:52:44
William Mak
fix(mep): Use project thresholds for apdex calculation (#37256)
false
Use project thresholds for apdex calculation (#37256)
fix
diff --git a/src/sentry/search/events/datasets/metrics.py b/src/sentry/search/events/datasets/metrics.py index 090471118e4c54..66623579c7885d 100644 --- a/src/sentry/search/events/datasets/metrics.py +++ b/src/sentry/search/events/datasets/metrics.py @@ -2,16 +2,24 @@ from typing import Any, Callable, Dict, List, Mapping, Optional, Union +import sentry_sdk +from django.utils.functional import cached_property from snuba_sdk import AliasedExpression, Column, Function from sentry import options from sentry.api.event_search import SearchFilter from sentry.exceptions import IncompatibleMetricsQuery, InvalidSearchQuery +from sentry.models.transaction_threshold import ( + TRANSACTION_METRICS, + ProjectTransactionThreshold, + ProjectTransactionThresholdOverride, +) from sentry.search.events import constants, fields from sentry.search.events.builder import MetricsQueryBuilder from sentry.search.events.datasets import field_aliases, filter_aliases from sentry.search.events.datasets.base import DatasetConfig from sentry.search.events.types import SelectType, WhereType +from sentry.utils.numbers import format_grouped_length from sentry.utils.snuba import is_duration_measurement, is_span_op_breakdown @@ -39,6 +47,7 @@ def field_alias_converter(self) -> Mapping[str, Callable[[str], SelectType]]: constants.PROJECT_NAME_ALIAS: self._resolve_project_slug_alias, constants.TEAM_KEY_TRANSACTION_ALIAS: self._resolve_team_key_transaction_alias, constants.TITLE_ALIAS: self._resolve_title_alias, + constants.PROJECT_THRESHOLD_CONFIG_ALIAS: lambda _: self._resolve_project_threshold_config, } def resolve_metric(self, value: str) -> int: @@ -567,6 +576,204 @@ def _resolve_project_slug_alias(self, alias: str) -> SelectType: return field_aliases.dry_run_default(self.builder, alias) return field_aliases.resolve_project_slug_alias(self.builder, alias) + @cached_property + def _resolve_project_threshold_config(self) -> SelectType: + """This is mostly duplicated code from the discover dataset version + TODO: try to make this more DRY with the discover version + """ + org_id = self.builder.params.get("organization_id") + project_ids = self.builder.params.get("project_id") + + project_threshold_configs = ( + ProjectTransactionThreshold.objects.filter( + organization_id=org_id, + project_id__in=project_ids, + ) + .order_by("project_id") + .values_list("project_id", "threshold", "metric") + ) + + transaction_threshold_configs = ( + ProjectTransactionThresholdOverride.objects.filter( + organization_id=org_id, + project_id__in=project_ids, + ) + .order_by("project_id") + .values_list("transaction", "project_id", "threshold", "metric") + ) + + num_project_thresholds = project_threshold_configs.count() + sentry_sdk.set_tag("project_threshold.count", num_project_thresholds) + sentry_sdk.set_tag( + "project_threshold.count.grouped", + format_grouped_length(num_project_thresholds, [10, 100, 250, 500]), + ) + + num_transaction_thresholds = transaction_threshold_configs.count() + sentry_sdk.set_tag("txn_threshold.count", num_transaction_thresholds) + sentry_sdk.set_tag( + "txn_threshold.count.grouped", + format_grouped_length(num_transaction_thresholds, [10, 100, 250, 500]), + ) + + if ( + num_project_thresholds + num_transaction_thresholds + > constants.MAX_QUERYABLE_TRANSACTION_THRESHOLDS + ): + raise InvalidSearchQuery( + f"Exceeded {constants.MAX_QUERYABLE_TRANSACTION_THRESHOLDS} configured transaction thresholds limit, try with fewer Projects." + ) + + # Arrays need to have toUint64 casting because clickhouse will define the type as the narrowest possible type + # that can store listed argument types, which means the comparison will fail because of mismatched types + project_thresholds = {} + project_threshold_config_keys = [] + project_threshold_config_values = [] + for project_id, threshold, metric in project_threshold_configs: + metric = TRANSACTION_METRICS[metric] + if ( + threshold == constants.DEFAULT_PROJECT_THRESHOLD + and metric == constants.DEFAULT_PROJECT_THRESHOLD_METRIC + ): + # small optimization, if the configuration is equal to the default, + # we can skip it in the final query + continue + + project_thresholds[project_id] = (metric, threshold) + project_threshold_config_keys.append(Function("toUInt64", [project_id])) + project_threshold_config_values.append((metric, threshold)) + + project_threshold_override_config_keys = [] + project_threshold_override_config_values = [] + for transaction, project_id, threshold, metric in transaction_threshold_configs: + metric = TRANSACTION_METRICS[metric] + if ( + project_id in project_thresholds + and threshold == project_thresholds[project_id][1] + and metric == project_thresholds[project_id][0] + ): + # small optimization, if the configuration is equal to the project + # configs, we can skip it in the final query + continue + + elif ( + project_id not in project_thresholds + and threshold == constants.DEFAULT_PROJECT_THRESHOLD + and metric == constants.DEFAULT_PROJECT_THRESHOLD_METRIC + ): + # small optimization, if the configuration is equal to the default + # and no project configs were set, we can skip it in the final query + continue + + transaction_id = self.resolve_tag_value(transaction) + # Don't add to the config if we can't resolve it + if transaction_id is None: + continue + project_threshold_override_config_keys.append( + (Function("toUInt64", [project_id]), (Function("toUInt64", [transaction_id]))) + ) + project_threshold_override_config_values.append((metric, threshold)) + + project_threshold_config_index: SelectType = Function( + "indexOf", + [ + project_threshold_config_keys, + self.builder.column("project_id"), + ], + constants.PROJECT_THRESHOLD_CONFIG_INDEX_ALIAS, + ) + + project_threshold_override_config_index: SelectType = Function( + "indexOf", + [ + project_threshold_override_config_keys, + (self.builder.column("project_id"), self.builder.column("transaction")), + ], + constants.PROJECT_THRESHOLD_OVERRIDE_CONFIG_INDEX_ALIAS, + ) + + def _project_threshold_config(alias: Optional[str] = None) -> SelectType: + if project_threshold_config_keys and project_threshold_config_values: + return Function( + "if", + [ + Function( + "equals", + [ + project_threshold_config_index, + 0, + ], + ), + ( + constants.DEFAULT_PROJECT_THRESHOLD_METRIC, + constants.DEFAULT_PROJECT_THRESHOLD, + ), + Function( + "arrayElement", + [ + project_threshold_config_values, + project_threshold_config_index, + ], + ), + ], + alias, + ) + + return Function( + "tuple", + [constants.DEFAULT_PROJECT_THRESHOLD_METRIC, constants.DEFAULT_PROJECT_THRESHOLD], + alias, + ) + + if project_threshold_override_config_keys and project_threshold_override_config_values: + return Function( + "if", + [ + Function( + "equals", + [ + project_threshold_override_config_index, + 0, + ], + ), + _project_threshold_config(), + Function( + "arrayElement", + [ + project_threshold_override_config_values, + project_threshold_override_config_index, + ], + ), + ], + constants.PROJECT_THRESHOLD_CONFIG_ALIAS, + ) + + return _project_threshold_config(constants.PROJECT_THRESHOLD_CONFIG_ALIAS) + + def _project_threshold_multi_if_function(self) -> SelectType: + """Accessed by `_resolve_apdex_function` and `_resolve_count_miserable_function`, + this returns the right duration value (for example, lcp or duration) based + on project or transaction thresholds that have been configured by the user. + """ + + return Function( + "multiIf", + [ + Function( + "equals", + [ + Function( + "tupleElement", + [self.builder.resolve_field_alias("project_threshold_config"), 1], + ), + "lcp", + ], + ), + self.resolve_metric("measurements.lcp"), + self.resolve_metric("transaction.duration"), + ], + ) + # Query Filters def _event_type_converter(self, search_filter: SearchFilter) -> Optional[WhereType]: """Not really a converter, check its transaction, error otherwise""" @@ -643,7 +850,7 @@ def _resolve_apdex_function( "equals", [self.builder.column(constants.METRIC_SATISFACTION_TAG_KEY), metric_tolerated] ) metric_condition = Function( - "equals", [Column("metric_id"), self.resolve_metric("transaction.duration")] + "equals", [Column("metric_id"), self._project_threshold_multi_if_function()] ) return Function( diff --git a/tests/snuba/api/endpoints/test_organization_events_mep.py b/tests/snuba/api/endpoints/test_organization_events_mep.py index b9587e37c010ce..b4362406f2b9d3 100644 --- a/tests/snuba/api/endpoints/test_organization_events_mep.py +++ b/tests/snuba/api/endpoints/test_organization_events_mep.py @@ -7,6 +7,10 @@ from sentry.discover.models import TeamKeyTransaction from sentry.exceptions import IncompatibleMetricsQuery, InvalidSearchQuery from sentry.models import ProjectTeam +from sentry.models.transaction_threshold import ( + ProjectTransactionThresholdOverride, + TransactionMetric, +) from sentry.search.events import constants from sentry.testutils import MetricsEnhancedPerformanceTestCase from sentry.testutils.helpers.datetime import before_now, iso_format @@ -1415,6 +1419,67 @@ def test_has_transaction(self): assert data[0]["p50(transaction.duration)"] == 1 assert meta["isMetricsData"] + def test_apdex_transaction_threshold(self): + ProjectTransactionThresholdOverride.objects.create( + transaction="foo_transaction", + project=self.project, + organization=self.project.organization, + threshold=600, + metric=TransactionMetric.LCP.value, + ) + ProjectTransactionThresholdOverride.objects.create( + transaction="bar_transaction", + project=self.project, + organization=self.project.organization, + threshold=600, + metric=TransactionMetric.LCP.value, + ) + self.store_transaction_metric( + 1, + tags={ + "transaction": "foo_transaction", + constants.METRIC_SATISFACTION_TAG_KEY: constants.METRIC_SATISFIED_TAG_VALUE, + }, + timestamp=self.min_ago, + ) + self.store_transaction_metric( + 1, + "measurements.lcp", + tags={ + "transaction": "bar_transaction", + constants.METRIC_SATISFACTION_TAG_KEY: constants.METRIC_SATISFIED_TAG_VALUE, + }, + timestamp=self.min_ago, + ) + response = self.do_request( + { + "field": [ + "transaction", + "apdex()", + ], + "orderby": ["apdex()"], + "query": "event.type:transaction", + "dataset": "metrics", + "per_page": 50, + } + ) + + assert len(response.data["data"]) == 2 + data = response.data["data"] + meta = response.data["meta"] + field_meta = meta["fields"] + + assert data[0]["transaction"] == "bar_transaction" + # Threshold is lcp based + assert data[0]["apdex()"] == 1 + assert data[1]["transaction"] == "foo_transaction" + # Threshold is lcp based + assert data[1]["apdex()"] == 0 + + assert meta["isMetricsData"] + assert field_meta["transaction"] == "string" + assert field_meta["apdex()"] == "number" + def test_apdex_satisfaction_param(self): for function in ["apdex(300)", "user_misery(300)", "count_miserable(user, 300)"]: query = {
4ee1ea91ce09d4f3976bcb3bc576aca9946194c0
2024-06-18 22:21:01
Armen Zambrano G
feat(related_issues): Free tier support for trace timeline and related issues (#72933)
false
Free tier support for trace timeline and related issues (#72933)
feat
diff --git a/static/app/views/issueDetails/traceTimeline/traceTimeline.spec.tsx b/static/app/views/issueDetails/traceTimeline/traceTimeline.spec.tsx index 05102db90ffe69..ce657e2a29d17e 100644 --- a/static/app/views/issueDetails/traceTimeline/traceTimeline.spec.tsx +++ b/static/app/views/issueDetails/traceTimeline/traceTimeline.spec.tsx @@ -15,7 +15,11 @@ jest.mock('sentry/utils/routeAnalytics/useRouteAnalyticsParams'); jest.mock('sentry/utils/analytics'); describe('TraceTimeline', () => { - const organization = OrganizationFixture(); + // Paid plans have global-views enabled + // Include project: -1 in all matchQuery calls to ensure we are looking at all projects + const organization = OrganizationFixture({ + features: ['global-views'], + }); // This creates the ApiException event const event = EventFixture({ dateCreated: '2024-01-24T09:09:03+00:00', @@ -72,12 +76,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: issuePlatformBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: discoverBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); render(<TraceTimeline event={event} />, {organization}); expect(await screen.findByLabelText('Current Event')).toBeInTheDocument(); @@ -94,12 +98,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: discoverBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); const {container} = render(<TraceTimeline event={event} />, {organization}); await waitFor(() => @@ -115,12 +119,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); const {container} = render(<TraceTimeline event={event} />, {organization}); await waitFor(() => @@ -136,12 +140,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: issuePlatformBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); render(<TraceTimeline event={event} />, {organization}); // Checking for the presence of seconds @@ -152,12 +156,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: issuePlatformBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); render(<TraceTimeline event={event} />, {organization}); expect(await screen.findByLabelText('Current Event')).toBeInTheDocument(); @@ -167,12 +171,12 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: issuePlatformBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); // I believe the call to projects is to determine what projects a user belongs to MockApiClient.addMockResponse({ @@ -182,7 +186,7 @@ describe('TraceTimeline', () => { render(<TraceTimeline event={event} />, { organization: OrganizationFixture({ - features: ['related-issues-issue-details-page'], + features: ['related-issues-issue-details-page', 'global-views'], }), }); @@ -201,7 +205,7 @@ describe('TraceTimeline', () => { { group_id: issuePlatformBody.data[0]['issue.id'], organization: OrganizationFixture({ - features: ['related-issues-issue-details-page'], + features: ['related-issues-issue-details-page', 'global-views'], }), } ); @@ -211,13 +215,13 @@ describe('TraceTimeline', () => { MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, body: emptyBody, - match: [MockApiClient.matchQuery({dataset: 'issuePlatform'})], + match: [MockApiClient.matchQuery({dataset: 'issuePlatform', project: -1})], }); MockApiClient.addMockResponse({ url: `/organizations/${organization.slug}/events/`, // Only 1 issue body: discoverBody, - match: [MockApiClient.matchQuery({dataset: 'discover'})], + match: [MockApiClient.matchQuery({dataset: 'discover', project: -1})], }); // I believe the call to projects is to determine what projects a user belongs to MockApiClient.addMockResponse({ @@ -227,7 +231,7 @@ describe('TraceTimeline', () => { render(<TraceTimeline event={event} />, { organization: OrganizationFixture({ - features: ['related-issues-issue-details-page'], + features: ['related-issues-issue-details-page', 'global-views'], }), }); @@ -244,4 +248,36 @@ describe('TraceTimeline', () => { trace_timeline_status: 'empty', }); }); + + it('works for plans with no global-views feature', async () => { + MockApiClient.addMockResponse({ + url: `/organizations/${organization.slug}/events/`, + body: issuePlatformBody, + match: [ + MockApiClient.matchQuery({ + dataset: 'issuePlatform', + // Since we don't have global-views, we only look at the current project + project: event.projectID, + }), + ], + }); + MockApiClient.addMockResponse({ + url: `/organizations/${organization.slug}/events/`, + body: emptyBody, + match: [ + MockApiClient.matchQuery({ + dataset: 'discover', + // Since we don't have global-views, we only look at the current project + project: event.projectID, + }), + ], + }); + + render(<TraceTimeline event={event} />, { + organization: OrganizationFixture({ + features: [], // No global-views feature + }), + }); + expect(await screen.findByLabelText('Current Event')).toBeInTheDocument(); + }); }); diff --git a/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx b/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx index 6ccc734bde8e65..fe572bf0af236a 100644 --- a/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx +++ b/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx @@ -43,6 +43,10 @@ export function useTraceTimelineEvents({event}: UseTraceTimelineEventsOptions): traceEvents: TimelineEvent[]; } { const organization = useOrganization(); + // If the org has global views, we want to look across all projects, + // otherwise, just look at the current project. + const hasGlobalViews = organization.features.includes('global-views'); + const project = hasGlobalViews ? -1 : event.projectID; const {start, end} = getTraceTimeRangeFromEvent(event); const traceId = event.contexts?.trace?.trace_id ?? ''; @@ -65,6 +69,7 @@ export function useTraceTimelineEvents({event}: UseTraceTimelineEventsOptions): sort: '-timestamp', start, end, + project: project, }, }, ], @@ -100,6 +105,7 @@ export function useTraceTimelineEvents({event}: UseTraceTimelineEventsOptions): sort: '-timestamp', start, end, + project: project, }, }, ],
a5d051b624080fca7c869d9778045e74ed3e5c99
2022-06-17 01:00:07
Dameli Ushbayeva
fix(perf): Do not set query.user_modified in the backend (#35754)
false
Do not set query.user_modified in the backend (#35754)
fix
diff --git a/src/sentry/api/endpoints/organization_events.py b/src/sentry/api/endpoints/organization_events.py index b7502b4eaa0240..6a0125f71030a1 100644 --- a/src/sentry/api/endpoints/organization_events.py +++ b/src/sentry/api/endpoints/organization_events.py @@ -85,9 +85,6 @@ def get(self, request: Request, organization) -> Response: sentry_sdk.set_tag("performance.metrics_enhanced", metrics_enhanced) allow_metric_aggregates = request.GET.get("preventMetricAggregates") != "1" - query_modified_by_user = request.GET.get("user_modified") - if query_modified_by_user in ["true", "false"]: - sentry_sdk.set_tag("query.user_modified", query_modified_by_user) referrer = ( referrer if referrer in ALLOWED_EVENTS_REFERRERS else "api.organization-events-v2" ) @@ -249,10 +246,6 @@ def get(self, request: Request, organization) -> Response: elif referrer not in ALLOWED_EVENTS_REFERRERS: referrer = "api.organization-events" - query_modified_by_user = request.GET.get("user_modified") - if query_modified_by_user in ["true", "false"]: - sentry_sdk.set_tag("query.user_modified", query_modified_by_user) - def data_fn(offset, limit): query_details = { "selected_columns": self.get_field_list(organization, request), diff --git a/src/sentry/api/endpoints/organization_events_stats.py b/src/sentry/api/endpoints/organization_events_stats.py index 21e9f88cca4081..476d1e2b206be5 100644 --- a/src/sentry/api/endpoints/organization_events_stats.py +++ b/src/sentry/api/endpoints/organization_events_stats.py @@ -156,10 +156,6 @@ def get(self, request: Request, organization: Organization) -> Response: allow_metric_aggregates = request.GET.get("preventMetricAggregates") != "1" sentry_sdk.set_tag("performance.metrics_enhanced", metrics_enhanced) - query_modified_by_user = request.GET.get("user_modified") - if query_modified_by_user in ["true", "false"]: - sentry_sdk.set_tag("query.user_modified", query_modified_by_user) - def get_event_stats( query_columns: Sequence[str], query: str,
0eac1a8a6d4af86960a2182ccfa797bf76b39152
2018-06-01 01:06:21
0x6a6f7368
build(travis): Finishing Touches Take 2 (#8617)
false
Finishing Touches Take 2 (#8617)
build
diff --git a/.travis.yml b/.travis.yml index 07371025c37207..ab99c9aa0d3428 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,5 +1,3 @@ -filter_secrets: false - dist: trusty sudo: required group: deprecated-2017Q4 @@ -13,9 +11,10 @@ branches: cache: yarn: true directories: - - node_modules - "${HOME}/virtualenv/python$(python -c 'import platform; print(platform.python_version())')" - - $HOME/google-cloud-sdk + - "${HOME}/.nvm/versions/node/v$(< .nvmrc)" + - node_modules + - "${HOME}/google-cloud-sdk" addons: apt: @@ -32,31 +31,33 @@ env: - SENTRY_SKIP_BACKEND_VALIDATION=1 - SOUTH_TESTS_MIGRATE=1 - DJANGO_VERSION=">=1.6.11,<1.7" - - NODE_VERSION="8.9.1" + # node's version is pinned by .nvmrc and is autodetected by `nvm install`. - YARN_VERSION="1.3.2" script: - make travis-lint-$TEST_SUITE - make travis-test-$TEST_SUITE - make travis-scan-$TEST_SUITE + # installing dependencies for after_* steps here ensures they get cached + # since those steps execute after travis runs `store build cache` + - pip install codecov + - npm install -g @zeus-ci/cli after_success: - - pip install codecov - codecov -e TEST_SUITE after_failure: - dmesg | tail -n 100 after_script: - - npm install -g @zeus-ci/cli - zeus upload -t "text/xml+xunit" junit.xml - - zeus upload -t "text/xml+xunit" jest.junit.xml - - zeus upload -t "text/xml+coverage" coverage.xml - - zeus upload -t "text/xml+coverage" coverage/cobertura-coverage.xml - - zeus upload -t "text/html+pytest" pytest.html - - zeus upload -t "text/plain+pycodestyle" flake8.pycodestyle.log - - zeus upload -t "text/xml+checkstyle" eslint.checkstyle.xml - - zeus upload -t "application/webpack-stats+json" webpack-stats.json + -t "text/xml+xunit" jest.junit.xml + -t "text/xml+coverage" coverage.xml + -t "text/xml+coverage" coverage/cobertura-coverage.xml + -t "text/html+pytest" pytest.html + -t "text/plain+pycodestyle" flake8.pycodestyle.log + -t "text/xml+checkstyle" eslint.checkstyle.xml + -t "application/webpack-stats+json" webpack-stats.json # each job in the matrix inherits `env/global` and uses everything above, # but custom `services`, `before_install`, `install`, and `before_script` directives @@ -104,25 +105,26 @@ matrix: - redis-server - postgresql before_install: - - nvm install "$NODE_VERSION" + - nvm install - npm install -g "yarn@${YARN_VERSION}" install: + - yarn install --pure-lockfile - pip install -e ".[dev,tests,optional]" - wget -N "http://chromedriver.storage.googleapis.com/$(curl https://chromedriver.storage.googleapis.com/LATEST_RELEASE)/chromedriver_linux64.zip" -P ~/ - unzip ~/chromedriver_linux64.zip -d ~/ - rm ~/chromedriver_linux64.zip - sudo install -m755 ~/chromedriver /usr/local/bin/ - - yarn install --pure-lockfile before_script: - psql -c 'create database sentry;' -U postgres - python: 2.7 env: TEST_SUITE=js before_install: - - nvm install "$NODE_VERSION" + - nvm install - npm install -g "yarn@${YARN_VERSION}" install: - yarn install --pure-lockfile + # TODO https://github.com/getsentry/sentry/issues/8451 - pip install $(cat requirements*.txt | grep -E 'click|pycodestyle') - python: 2.7 @@ -189,8 +191,6 @@ matrix: - tar -xzf credentials.tar.gz # Use the decrypted service account credentials to authenticate the command line tool - gcloud auth activate-service-account --key-file client-secret.json - # Travis doesn't "inherit" steps like before_install in the build matrix, so we have to explicitly install our package managers - - nvm install "$NODE_VERSION" - npm install -g "yarn@${YARN_VERSION}" install: - yarn install --pure-lockfile
1bed1c8292822669d69e5126e9f9f57ef91f7e89
2024-09-17 23:43:40
Michael Sun
fix(custom-views): Stop tabs from animating on load (#77641)
false
Stop tabs from animating on load (#77641)
fix
diff --git a/static/app/components/draggableTabs/draggableTabList.tsx b/static/app/components/draggableTabs/draggableTabList.tsx index 7284a09a5aa6ad..674b366b2bc55c 100644 --- a/static/app/components/draggableTabs/draggableTabList.tsx +++ b/static/app/components/draggableTabs/draggableTabList.tsx @@ -155,7 +155,13 @@ function Tabs({ return ( <TabListWrap {...tabListProps} className={className} ref={tabListRef}> - <ReorderGroup axis="x" values={values} onReorder={onReorder} as="div"> + <ReorderGroup + axis="x" + values={values} + onReorder={onReorder} + as="div" + initial={false} + > {tabs.map((item, i) => ( <Fragment key={item.key}> <TabItemWrap @@ -183,6 +189,7 @@ function Tabs({ onDragEnd={() => setIsDragging(false)} onHoverStart={() => setHoveringKey(item.key)} onHoverEnd={() => setHoveringKey(null)} + initial={false} > <div key={item.key}> <Tab @@ -203,6 +210,7 @@ function Tabs({ hoveringKey !== item.key && state.collection.getKeyAfter(item.key) !== hoveringKey } + initial={false} /> </Fragment> ))} diff --git a/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx b/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx index 27bb1bb2f4b4c2..091d3640d28250 100644 --- a/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx +++ b/static/app/views/issueList/groupSearchViewTabs/draggableTabBar.tsx @@ -363,7 +363,12 @@ export function DraggableTabBar({ onChange={newLabel => handleOnTabRenamed(newLabel.trim(), tab.key)} isSelected={tabListState?.selectedKey === tab.key} /> - {tabListState?.selectedKey === tab.key && ( + {/* If tablistState isn't initialized, we want to load the elipsis menu + for the initial tab, that way it won't load in a second later + and cause the tabs to shift and animate on load. + */} + {((tabListState && tabListState?.selectedKey === tab.key) || + (!tabListState && tab.key === initialTabKey)) && ( <DraggableTabMenuButton hasUnsavedChanges={!!tab.unsavedChanges} menuOptions={makeMenuOptions(tab)}
56b0aeb42b735e262e5c3ed4b98f34e3b437ef7e
2024-04-05 22:20:42
David Wang
ref(crons): Instrument broken monitors task with timing metrics (#68353)
false
Instrument broken monitors task with timing metrics (#68353)
ref
diff --git a/src/sentry/monitors/tasks/detect_broken_monitor_envs.py b/src/sentry/monitors/tasks/detect_broken_monitor_envs.py index 57fd7f98ea5d08..983482e20e2622 100644 --- a/src/sentry/monitors/tasks/detect_broken_monitor_envs.py +++ b/src/sentry/monitors/tasks/detect_broken_monitor_envs.py @@ -22,6 +22,7 @@ MonitorIncident, ) from sentry.tasks.base import instrumented_task +from sentry.utils import metrics from sentry.utils.email import MessageBuilder from sentry.utils.http import absolute_uri from sentry.utils.query import RangeQuerySetWrapper @@ -130,6 +131,9 @@ def detect_broken_monitor_envs(): except Organization.DoesNotExist: continue + # Record how long it takes to process this org + org_process_start_time = django_timezone.now() + # Map user email to a dictionary of monitors and their earliest incident start date amongst its broken environments user_broken_envs: dict[str, dict[str, Any]] = defaultdict( lambda: defaultdict( @@ -153,6 +157,9 @@ def detect_broken_monitor_envs(): order_by="starting_timestamp", step=1000, ): + # Record how long it takes to process this org's incident + org_incident_process_start_time = django_timezone.now() + # Verify that the most recent check-ins have been failing recent_checkins = ( MonitorCheckIn.objects.filter(monitor_environment=open_incident.monitor_environment) @@ -199,6 +206,15 @@ def detect_broken_monitor_envs(): user_muted_envs, user.user_email, open_incident, project, environment_name ) + metrics.timing( + "crons.detect_broken_monitor_org_incident_time", + django_timezone.now().timestamp() - org_incident_process_start_time.timestamp(), + tags={"incident": open_incident.id}, + ) + + # Record how long it takes to send all emails for an org + org_email_sending_start_time = django_timezone.now() + # After accumulating all users within the org and which monitors to email them, send the emails for user_email, broken_monitors in user_broken_envs.items(): context = { @@ -232,7 +248,19 @@ def detect_broken_monitor_envs(): ) message.send_async([user_email]) + metrics.timing( + "crons.detect_broken_monitor_org_email_time", + django_timezone.now().timestamp() - org_email_sending_start_time.timestamp(), + tags={"org_id": org_id}, + ) + # mark all open detections for this org as having had their email sent MonitorEnvBrokenDetection.objects.filter( monitor_incident__in=orgs_open_incidents, user_notified_timestamp=None ).update(user_notified_timestamp=django_timezone.now()) + + metrics.timing( + "crons.detect_broken_monitor_org_time", + django_timezone.now().timestamp() - org_process_start_time.timestamp(), + tags={"org_id": org_id}, + )
cd71a09f890e4ae5efbf4828454695d83e75ce69
2023-04-05 18:02:12
George Gritsouk
fix(perf-issues): Fix subject substitution for Performance issues (#46914)
false
Fix subject substitution for Performance issues (#46914)
fix
diff --git a/fixtures/emails/performance.txt b/fixtures/emails/performance.txt index d05e2629aa8544..ae0ac46323b492 100644 --- a/fixtures/emails/performance.txt +++ b/fixtures/emails/performance.txt @@ -25,6 +25,7 @@ Tags * level = info * runtime = CPython 3.8.9 * runtime.name = CPython +* sentry:release = 0.1 * sentry:user = ip:127.0.0.1 * transaction = /books/ * url = http://127.0.0.1:9007/books/ diff --git a/src/sentry/data/samples/transaction-n-plus-one.json b/src/sentry/data/samples/transaction-n-plus-one.json index f86fe8b8894cf4..6ffe76c8d91ee2 100644 --- a/src/sentry/data/samples/transaction-n-plus-one.json +++ b/src/sentry/data/samples/transaction-n-plus-one.json @@ -9,6 +9,7 @@ ["device", "Mac"], ["device.family", "Mac"], ["environment", "production"], + ["sentry:release", "0.1"], ["http.status_code", "200"], ["level", "info"], ["runtime", "CPython 3.8.9"], diff --git a/src/sentry/eventstore/models.py b/src/sentry/eventstore/models.py index bc49c66078e88a..9c8a87911749c5 100644 --- a/src/sentry/eventstore/models.py +++ b/src/sentry/eventstore/models.py @@ -778,6 +778,9 @@ def __getitem__(self, name: str) -> str: if name.startswith("tag:"): name = name[4:] value = self.event.get_tag(self.tag_aliases.get(name, name)) + if value is None: + value = self.event.get_tag(name) + if value is None: raise KeyError return str(value) @@ -790,11 +793,13 @@ def __getitem__(self, name: str) -> str: elif name == "orgID": return cast(str, self.event.organization.slug) elif name == "title": - return ( - self.event.occurrence.issue_title - if getattr(self.event, "occurrence", None) - else self.event.title - ) + if getattr(self.event, "occurrence", None): + return self.event.occurrence.issue_title + elif self.event.group and self.event.group.issue_category == GroupCategory.PERFORMANCE: + return self.event.group.issue_type.description + else: + return self.event.title + elif name == "issueType": return self.event.group.issue_type.description raise KeyError diff --git a/tests/sentry/eventstore/test_models.py b/tests/sentry/eventstore/test_models.py index 612475a117dec4..77ed00c4ac2db8 100644 --- a/tests/sentry/eventstore/test_models.py +++ b/tests/sentry/eventstore/test_models.py @@ -12,6 +12,7 @@ from sentry.models import Environment from sentry.snuba.dataset import Dataset from sentry.testutils import TestCase +from sentry.testutils.cases import PerformanceIssueTestCase from sentry.testutils.helpers.datetime import before_now, iso_format from sentry.testutils.silo import region_silo_test from sentry.utils import snuba @@ -19,7 +20,7 @@ @region_silo_test -class EventTest(TestCase): +class EventTest(TestCase, PerformanceIssueTestCase): def test_pickling_compat(self): event = self.store_event( data={ @@ -105,6 +106,15 @@ def test_email_subject_with_template(self): assert event1.get_email_subject() == "BAR-1 - production@0 $ baz ${tag:invalid} $invalid" + def test_transaction_email_subject(self): + self.project.update_option( + "mail:subject_template", + "$shortID - ${tag:environment}@${tag:release} $title", + ) + + event = self.create_performance_issue() + assert event.get_email_subject() == "BAR-1 - [email protected] N+1 Query" + def test_as_dict_hides_client_ip(self): event = self.store_event( data={"sdk": {"name": "foo", "version": "1.0", "client_ip": "127.0.0.1"}},
533333f2840bfadf6749b989eaeb9aa872ad0e77
2019-03-13 20:55:53
Bruno Garcia
feat(sentrypad): Cap breadcrumbs per the largest count (#12392)
false
Cap breadcrumbs per the largest count (#12392)
feat
diff --git a/src/sentry/lang/native/minidump.py b/src/sentry/lang/native/minidump.py index 3cdfa313d4beb0..8d15cae705adb1 100644 --- a/src/sentry/lang/native/minidump.py +++ b/src/sentry/lang/native/minidump.py @@ -145,6 +145,10 @@ def merge_attached_breadcrumbs(mpack_breadcrumbs, data): if isinstance(c, dict) and c.get('timestamp') is not None), None) new_crumb = next((c for c in reversed(breadcrumbs) if isinstance( c, dict) and c.get('timestamp') is not None), None) + + # cap the breadcrumbs to the highest count of either file + cap = max(len(current_crumbs), len(breadcrumbs)) + if current_crumb is not None and new_crumb is not None: if dp.parse(current_crumb['timestamp']) > dp.parse(new_crumb['timestamp']): data['breadcrumbs'] = breadcrumbs + current_crumbs @@ -153,6 +157,8 @@ def merge_attached_breadcrumbs(mpack_breadcrumbs, data): else: data['breadcrumbs'] = current_crumbs + breadcrumbs + data['breadcrumbs'] = data['breadcrumbs'][-cap:] + def is_valid_module_id(id): return id is not None and id != '000000000000000000000000000000000' diff --git a/tests/sentry/lang/native/test_minidump.py b/tests/sentry/lang/native/test_minidump.py index 7d9b6f95a2c75d..8cd0837802ebca 100644 --- a/tests/sentry/lang/native/test_minidump.py +++ b/tests/sentry/lang/native/test_minidump.py @@ -1125,20 +1125,58 @@ def test_merge_attached_breadcrumbs_timestamp_ordered(): merge_attached_breadcrumbs(MockFile(mpack_crumb1), event) assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' - mpack_crumb2 = msgpack.packb({'timestamp': '0001-01-01T01:00:01Z'}) - merge_attached_breadcrumbs(MockFile(mpack_crumb2), event) + crumbs_file2 = bytearray() + crumbs_file2.extend(msgpack.packb({'timestamp': '0001-01-01T01:00:01Z'})) + # File with 2 items to extend cap + crumbs_file2.extend(msgpack.packb({'timestamp': '0001-01-01T01:00:01Z'})) + merge_attached_breadcrumbs(MockFile(crumbs_file2), event) assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:01Z' assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:02Z' mpack_crumb3 = msgpack.packb({'timestamp': '0001-01-01T01:00:03Z'}) merge_attached_breadcrumbs(MockFile(mpack_crumb3), event) - assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:01Z' - assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:02Z' - assert event['breadcrumbs'][2]['timestamp'] == '0001-01-01T01:00:03Z' + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:03Z' mpack_crumb4 = msgpack.packb({'timestamp': '0001-01-01T01:00:00Z'}) merge_attached_breadcrumbs(MockFile(mpack_crumb4), event) - assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:00Z' + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:03Z' + + +def test_merge_attached_breadcrumbs_capped(): + # Crumbs are capped by the largest file + event = {} + + crumbs_file1 = bytearray() + for i in range(0, 2): + crumbs_file1.extend(msgpack.packb({'timestamp': '0001-01-01T01:00:01Z'})) + + merge_attached_breadcrumbs(MockFile(crumbs_file1), event) + assert len(event['breadcrumbs']) == 2 + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:01Z' assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:01Z' + + crumbs_file2 = bytearray() + for i in range(0, 3): + crumbs_file2.extend(msgpack.packb({'timestamp': '0001-01-01T01:00:02Z'})) + + merge_attached_breadcrumbs(MockFile(crumbs_file2), event) + assert len(event['breadcrumbs']) == 3 + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:02Z' assert event['breadcrumbs'][2]['timestamp'] == '0001-01-01T01:00:02Z' - assert event['breadcrumbs'][3]['timestamp'] == '0001-01-01T01:00:03Z' + + crumbs_file3 = msgpack.packb({'timestamp': '0001-01-01T01:00:03Z'}) + merge_attached_breadcrumbs(MockFile(crumbs_file3), event) + assert len(event['breadcrumbs']) == 3 + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][2]['timestamp'] == '0001-01-01T01:00:03Z' + + crumbs_file4 = msgpack.packb({'timestamp': '0001-01-01T01:00:04Z'}) + merge_attached_breadcrumbs(MockFile(crumbs_file4), event) + assert len(event['breadcrumbs']) == 3 + assert event['breadcrumbs'][0]['timestamp'] == '0001-01-01T01:00:02Z' + assert event['breadcrumbs'][1]['timestamp'] == '0001-01-01T01:00:03Z' + assert event['breadcrumbs'][2]['timestamp'] == '0001-01-01T01:00:04Z'
cb5bd49ca198ea401ca5d6b1692ebf3c39851ac9
2024-12-06 07:53:45
Raj Joshi
nit(oauth): surface error when token exchange fails in oauth (#81769)
false
surface error when token exchange fails in oauth (#81769)
nit
diff --git a/src/sentry/identity/oauth2.py b/src/sentry/identity/oauth2.py index d5b6614eb720a0..f7e7b521956c0b 100644 --- a/src/sentry/identity/oauth2.py +++ b/src/sentry/identity/oauth2.py @@ -357,7 +357,7 @@ def dispatch(self, request: Request, pipeline) -> HttpResponse: lifecycle.record_failure( "token_exchange_error", extra={"failure_info": ERR_INVALID_STATE} ) - return pipeline.error(ERR_INVALID_STATE) + return pipeline.error(f"{ERR_INVALID_STATE}\nError: {error}") if state != pipeline.fetch_state("state"): pipeline.logger.info( @@ -384,7 +384,7 @@ def dispatch(self, request: Request, pipeline) -> HttpResponse: if "error" in data: pipeline.logger.info("identity.token-exchange-error", extra={"error": data["error"]}) - return pipeline.error(ERR_TOKEN_RETRIEVAL) + return pipeline.error(f"{ERR_TOKEN_RETRIEVAL}\nError: {data['error']}") # we can either expect the API to be implicit and say "im looking for # blah within state data" or we need to pass implementation + call a
1a27fb624b82ba065fe658941963459ef7cbcb68
2018-07-25 04:30:06
Jess MacQueen
ref(integrations): Move config saving to method
false
Move config saving to method
ref
diff --git a/src/sentry/api/endpoints/organization_integration_details.py b/src/sentry/api/endpoints/organization_integration_details.py index 86fb7d805a35dc..ac70304f772096 100644 --- a/src/sentry/api/endpoints/organization_integration_details.py +++ b/src/sentry/api/endpoints/organization_integration_details.py @@ -6,7 +6,7 @@ OrganizationEndpoint, OrganizationIntegrationsPermission ) from sentry.api.serializers import serialize -from sentry.models import OrganizationIntegration, ProjectIntegration +from sentry.models import Integration, OrganizationIntegration, ProjectIntegration class OrganizationIntegrationDetailsEndpoint(OrganizationEndpoint): @@ -39,15 +39,14 @@ def delete(self, request, organization, integration_id): def post(self, request, organization, integration_id): try: - integration = OrganizationIntegration.objects.get( - integration_id=integration_id, - organization=organization, + integration = Integration.objects.get( + id=integration_id, + organizations=organization, ) - except OrganizationIntegration.DoesNotExist: + except Integration.DoesNotExist: raise Http404 - config = integration.config - config.update(request.DATA) - integration.update(config=config) + installation = integration.get_installation(organization.id) + installation.update_organization_config(request.DATA) return self.respond(status=200) diff --git a/src/sentry/integrations/base.py b/src/sentry/integrations/base.py index 43135d4ff0132e..a0d3e2464122fa 100644 --- a/src/sentry/integrations/base.py +++ b/src/sentry/integrations/base.py @@ -189,6 +189,14 @@ def get_organization_config(self): """ return [] + def update_organization_config(self, data): + """ + Update the configuration field for an organization integration. + """ + config = self.org_integration.config + config.update(data) + self.org_integration.update(config=config) + def get_project_config(self): """ Provides configuration for the integration on a per-project
e94366f088e997e33cb2b082c770605816bf1dc4
2018-05-18 02:26:46
Jess MacQueen
ref: Rename group integration details endpoint to match convention
false
Rename group integration details endpoint to match convention
ref
diff --git a/src/sentry/api/endpoints/group_integration_details.py b/src/sentry/api/endpoints/group_integration_details.py index 5714fa75187215..54d07a5aebb248 100644 --- a/src/sentry/api/endpoints/group_integration_details.py +++ b/src/sentry/api/endpoints/group_integration_details.py @@ -11,7 +11,7 @@ from sentry.models import ExternalIssue, GroupLink, OrganizationIntegration -class GroupIntegrationDetails(GroupEndpoint): +class GroupIntegrationDetailsEndpoint(GroupEndpoint): def get(self, request, group, integration_id): # Keep link/create separate since create will likely require # many external API calls that aren't necessary if the user is diff --git a/src/sentry/api/urls.py b/src/sentry/api/urls.py index ee76a717b97ef7..3f4e4e6dd635fe 100644 --- a/src/sentry/api/urls.py +++ b/src/sentry/api/urls.py @@ -28,7 +28,7 @@ from .endpoints.group_events_latest import GroupEventsLatestEndpoint from .endpoints.group_events_oldest import GroupEventsOldestEndpoint from .endpoints.group_hashes import GroupHashesEndpoint -from .endpoints.group_integration_details import GroupIntegrationDetails +from .endpoints.group_integration_details import GroupIntegrationDetailsEndpoint from .endpoints.group_notes import GroupNotesEndpoint from .endpoints.group_notes_details import GroupNotesDetailsEndpoint from .endpoints.group_participants import GroupParticipantsEndpoint @@ -957,7 +957,7 @@ ), url( r'^(?:issues|groups)/(?P<issue_id>\d+)/integrations/(?P<integration_id>[^\/]+)/$', - GroupIntegrationDetails.as_view(), + GroupIntegrationDetailsEndpoint.as_view(), name='sentry-api-0-group-integration-details' ), # Load plugin group urls
a1b79cb6f0febb3a014d1a844bc411aa4dfc6657
2023-01-18 02:35:31
Leander Rodrigues
fix(integrations): Fix issue sync endpoint and add test (#43347)
false
Fix issue sync endpoint and add test (#43347)
fix
diff --git a/src/sentry/api/endpoints/organization_integration_issues.py b/src/sentry/api/endpoints/organization_integration_issues.py index f108b559c53836..8eee264ad0b60c 100644 --- a/src/sentry/api/endpoints/organization_integration_issues.py +++ b/src/sentry/api/endpoints/organization_integration_issues.py @@ -4,6 +4,7 @@ from sentry.api.base import region_silo_endpoint from sentry.api.bases.organization_integrations import OrganizationIntegrationBaseEndpoint from sentry.integrations.mixins import IssueSyncMixin +from sentry.services.hybrid_cloud.integration import integration_service @region_silo_endpoint @@ -18,7 +19,9 @@ def put(self, request: Request, organization, integration_id) -> Response: :pparam string integration_id: the id of the integration """ integration = self.get_integration(organization, integration_id) - install = integration.get_installation(organization.id) + install = integration_service.get_installation( + integration=integration, organization_id=organization.id + ) if isinstance(install, IssueSyncMixin): install.migrate_issues() return Response(status=204) diff --git a/tests/sentry/api/endpoints/test_organization_integration_issues.py b/tests/sentry/api/endpoints/test_organization_integration_issues.py new file mode 100644 index 00000000000000..533edef3e3e0b1 --- /dev/null +++ b/tests/sentry/api/endpoints/test_organization_integration_issues.py @@ -0,0 +1,40 @@ +from unittest.mock import patch + +from sentry.testutils import APITestCase +from sentry.testutils.silo import region_silo_test + + +@region_silo_test(stable=True) +class OrganizationIntegrationIssuesTest(APITestCase): + def setUp(self): + super().setUp() + self.login_as(self.user) + self.organization = self.create_organization(owner=self.user) + + def get_path(self, integration_id): + return ( + f"/api/0/organizations/{self.organization.slug}/integrations/{integration_id}/issues/" + ) + + def test_no_integration(self): + path = self.get_path(integration_id=-1) + response = self.client.put(path, format="json") + assert response.status_code == 404 + + def test_not_issue_integration(self): + integration = self.create_integration( + organization=self.organization, provider="slack", external_id="slack:1" + ) + path = self.get_path(integration_id=integration.id) + response = self.client.put(path, format="json") + assert response.status_code == 400 + + @patch("sentry.integrations.jira.integration.JiraIntegration.migrate_issues") + def test_simple(self, mock_migrate_issues): + integration = self.create_integration( + organization=self.organization, provider="jira", external_id="jira:1" + ) + path = self.get_path(integration_id=integration.id) + response = self.client.put(path, format="json") + assert response.status_code == 204 + assert mock_migrate_issues.called
88630de1b81f1ffcc6533e7a1d0da1479e0c3b90
2022-10-21 18:37:35
Shruthi
feat(mobile-exp): Paginate through single screenshots in gallery (#40260)
false
Paginate through single screenshots in gallery (#40260)
feat
diff --git a/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.spec.tsx b/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.spec.tsx new file mode 100644 index 00000000000000..53844fb57a1025 --- /dev/null +++ b/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.spec.tsx @@ -0,0 +1,142 @@ +import {initializeOrg} from 'sentry-test/initializeOrg'; +import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary'; + +import {ModalRenderProps} from 'sentry/actionCreators/modal'; +import Modal from 'sentry/components/events/eventTagsAndScreenshot/screenshot/modal'; +import GroupStore from 'sentry/stores/groupStore'; +import ProjectsStore from 'sentry/stores/projectsStore'; +import {EventAttachment, Project} from 'sentry/types'; + +const stubEl = (props: {children?: React.ReactNode}) => <div>{props.children}</div>; + +function renderModal({ + initialData: {organization, routerContext}, + eventAttachment, + projectSlug, + attachmentIndex, + attachments, + enablePagination, + groupId, +}: { + eventAttachment: EventAttachment; + initialData: any; + projectSlug: Project['slug']; + attachmentIndex?: number; + attachments?: EventAttachment[]; + enablePagination?: boolean; + groupId?: string; +}) { + return render( + <Modal + Header={stubEl} + Footer={stubEl as ModalRenderProps['Footer']} + Body={stubEl as ModalRenderProps['Body']} + CloseButton={stubEl} + closeModal={() => undefined} + onDelete={jest.fn()} + onDownload={jest.fn()} + orgSlug={organization.slug} + projectSlug={projectSlug} + eventAttachment={eventAttachment} + downloadUrl="" + pageLinks={ + '<http://localhost/api/0/issues/group-id/attachments/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' + + '<http://localhost/api/0/issues/group-id/attachments/?cursor=0:6:0>; rel="next"; results="true"; cursor="0:6:0"' + } + attachments={attachments} + attachmentIndex={attachmentIndex} + groupId={groupId} + enablePagination={enablePagination} + />, + { + context: routerContext, + organization, + } + ); +} + +describe('Modals -> ScreenshotModal', function () { + let initialData; + let project; + let getAttachmentsMock; + beforeEach(() => { + initialData = initializeOrg({ + organization: TestStubs.Organization({features: ['mobile-screenshot-gallery']}), + router: { + params: {orgId: 'org-slug', groupId: 'group-id'}, + location: {query: {types: 'event.screenshot'}}, + }, + } as Parameters<typeof initializeOrg>[0]); + project = TestStubs.Project(); + ProjectsStore.loadInitialData([project]); + GroupStore.init(); + + getAttachmentsMock = MockApiClient.addMockResponse({ + url: '/issues/group-id/attachments/', + body: [TestStubs.EventAttachment()], + headers: { + link: + '<http://localhost/api/0/issues/group-id/attachments/?cursor=0:0:1>; rel="previous"; results="false"; cursor="0:0:1",' + + '<http://localhost/api/0/issues/group-id/attachments/?cursor=0:6:0>; rel="next"; results="true"; cursor="0:10:0"', + }, + }); + }); + + afterEach(() => { + MockApiClient.clearMockResponses(); + }); + it('paginates single screenshots correctly', function () { + const eventAttachment = TestStubs.EventAttachment(); + renderModal({ + eventAttachment, + initialData, + projectSlug: project.slug, + attachmentIndex: 0, + attachments: [ + eventAttachment, + TestStubs.EventAttachment({id: '2', event_id: 'new event id'}), + TestStubs.EventAttachment({id: '3'}), + TestStubs.EventAttachment({id: '4'}), + TestStubs.EventAttachment({id: '5'}), + TestStubs.EventAttachment({id: '6'}), + ], + enablePagination: true, + groupId: 'group-id', + }); + expect(screen.getByRole('button', {name: 'Previous'})).toBeDisabled(); + userEvent.click(screen.getByRole('button', {name: 'Next'})); + + expect(screen.getByText('new event id')).toBeInTheDocument(); + expect(screen.getByRole('button', {name: 'Previous'})).toBeEnabled(); + }); + + it('fetches a new batch of screenshots correctly', async function () { + const eventAttachment = TestStubs.EventAttachment(); + renderModal({ + eventAttachment, + initialData, + projectSlug: project.slug, + attachmentIndex: 5, + attachments: [ + TestStubs.EventAttachment({id: '2'}), + TestStubs.EventAttachment({id: '3'}), + TestStubs.EventAttachment({id: '4'}), + TestStubs.EventAttachment({id: '5'}), + TestStubs.EventAttachment({id: '6'}), + eventAttachment, + ], + enablePagination: true, + groupId: 'group-id', + }); + userEvent.click(screen.getByRole('button', {name: 'Next'})); + + await waitFor(() => { + expect(getAttachmentsMock).toHaveBeenCalledWith( + '/issues/group-id/attachments/', + expect.objectContaining({ + query: expect.objectContaining({cursor: '0:6:0'}), + }) + ); + }); + }); +}); diff --git a/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.tsx b/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.tsx index 8fed1436014a09..65008358ed6d9d 100644 --- a/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.tsx +++ b/static/app/components/events/eventTagsAndScreenshot/screenshot/modal.tsx @@ -1,4 +1,4 @@ -import {Fragment} from 'react'; +import {Fragment, useState} from 'react'; import {css} from '@emotion/react'; import styled from '@emotion/styled'; @@ -8,15 +8,21 @@ import Buttonbar from 'sentry/components/buttonBar'; import Confirm from 'sentry/components/confirm'; import DateTime from 'sentry/components/dateTime'; import {getRelativeTimeFromEventDateCreated} from 'sentry/components/events/contexts/utils'; +import Link from 'sentry/components/links/link'; import NotAvailable from 'sentry/components/notAvailable'; +import {CursorHandler} from 'sentry/components/pagination'; import {t} from 'sentry/locale'; import space from 'sentry/styles/space'; -import {EventAttachment, Organization, Project} from 'sentry/types'; +import {EventAttachment, IssueAttachment, Organization, Project} from 'sentry/types'; import {Event} from 'sentry/types/event'; import {defined, formatBytesBase2} from 'sentry/utils'; import getDynamicText from 'sentry/utils/getDynamicText'; +import parseLinkHeader from 'sentry/utils/parseLinkHeader'; +import useApi from 'sentry/utils/useApi'; +import {MAX_SCREENSHOTS_PER_PAGE} from 'sentry/views/organizationGroupDetails/groupEventAttachments/groupEventAttachments'; import ImageVisualization from './imageVisualization'; +import ScreenshotPagination from './screenshotPagination'; type Props = ModalRenderProps & { downloadUrl: string; @@ -25,7 +31,12 @@ type Props = ModalRenderProps & { onDownload: () => void; orgSlug: Organization['slug']; projectSlug: Project['slug']; + attachmentIndex?: number; + attachments?: EventAttachment[]; + enablePagination?: boolean; event?: Event; + groupId?: string; + pageLinks?: string | null | undefined; }; function Modal({ @@ -39,13 +50,82 @@ function Modal({ onDelete, downloadUrl, onDownload, + pageLinks: initialPageLinks, + attachmentIndex, + attachments, + enablePagination, + groupId, }: Props) { - const {dateCreated, size, mimetype} = eventAttachment; + const api = useApi(); + + const [currentEventAttachment, setCurrentAttachment] = + useState<EventAttachment>(eventAttachment); + const [currentAttachmentIndex, setCurrentAttachmentIndex] = useState< + number | undefined + >(attachmentIndex); + const [memoizedAttachments, setMemoizedAttachments] = useState< + IssueAttachment[] | undefined + >(attachments); + + const [pageLinks, setPageLinks] = useState<string | null | undefined>(initialPageLinks); + + const handleCursor: CursorHandler = (cursor, _pathname, query, delta) => { + if (defined(currentAttachmentIndex) && memoizedAttachments?.length) { + const newAttachmentIndex = currentAttachmentIndex + delta; + if (newAttachmentIndex === MAX_SCREENSHOTS_PER_PAGE || newAttachmentIndex === -1) { + api + .requestPromise(`/issues/${groupId}/attachments/`, { + method: 'GET', + includeAllArgs: true, + query: { + ...query, + per_page: MAX_SCREENSHOTS_PER_PAGE, + types: undefined, + screenshot: 1, + cursor, + }, + }) + .then(([data, _, resp]) => { + if (newAttachmentIndex === MAX_SCREENSHOTS_PER_PAGE) { + setCurrentAttachmentIndex(0); + setCurrentAttachment(data[0]); + } else { + setCurrentAttachmentIndex(MAX_SCREENSHOTS_PER_PAGE - 1); + setCurrentAttachment(data[MAX_SCREENSHOTS_PER_PAGE - 1]); + } + setMemoizedAttachments(data); + setPageLinks(resp?.getResponseHeader('Link')); + }); + return; + } + setCurrentAttachmentIndex(newAttachmentIndex); + setCurrentAttachment(memoizedAttachments[newAttachmentIndex]); + } + }; + + const {dateCreated, size, mimetype} = currentEventAttachment; + const links = pageLinks ? parseLinkHeader(pageLinks) : undefined; + const previousDisabled = + links?.previous?.results === false && currentAttachmentIndex === 0; + const nextDisabled = links?.next?.results === false && currentAttachmentIndex === 5; + return ( <Fragment> <Header closeButton>{t('Screenshot')}</Header> <Body> <GeralInfo> + {groupId && enablePagination && ( + <Fragment> + <Label>{t('Event ID')}</Label> + <Value> + <Title + to={`/organizations/${orgSlug}/issues/${groupId}/events/${currentEventAttachment.event_id}/`} + > + {currentEventAttachment.event_id} + </Title> + </Value> + </Fragment> + )} <Label coloredBg>{t('Date Created')}</Label> <Value coloredBg> {dateCreated ? ( @@ -76,10 +156,10 @@ function Modal({ </GeralInfo> <StyledImageVisualization - attachment={eventAttachment} + attachment={currentEventAttachment} orgId={orgSlug} projectId={projectSlug} - eventId={eventAttachment.event_id} + eventId={currentEventAttachment.event_id} /> </Body> <Footer> @@ -98,6 +178,14 @@ function Modal({ <Button onClick={onDownload} href={downloadUrl}> {t('Download')} </Button> + {enablePagination && ( + <ScreenshotPagination + onCursor={handleCursor} + pageLinks={pageLinks} + previousDisabled={previousDisabled} + nextDisabled={nextDisabled} + /> + )} </Buttonbar> </Footer> </Fragment> @@ -134,8 +222,13 @@ const StyledImageVisualization = styled(ImageVisualization)` } `; +const Title = styled(Link)` + ${p => p.theme.overflowEllipsis}; + font-weight: normal; +`; + export const modalCss = css` width: auto; height: 100%; - max-width: 100%; + max-width: 700px; `; diff --git a/static/app/components/events/eventTagsAndScreenshot/screenshot/screenshotPagination.tsx b/static/app/components/events/eventTagsAndScreenshot/screenshot/screenshotPagination.tsx new file mode 100644 index 00000000000000..cd4e846bebffb9 --- /dev/null +++ b/static/app/components/events/eventTagsAndScreenshot/screenshot/screenshotPagination.tsx @@ -0,0 +1,72 @@ +// eslint-disable-next-line no-restricted-imports +import {withRouter, WithRouterProps} from 'react-router'; +import styled from '@emotion/styled'; + +import Button from 'sentry/components/button'; +import ButtonBar from 'sentry/components/buttonBar'; +import {CursorHandler} from 'sentry/components/pagination'; +import {IconChevron} from 'sentry/icons'; +import {t} from 'sentry/locale'; +import parseLinkHeader from 'sentry/utils/parseLinkHeader'; + +type Props = WithRouterProps & { + nextDisabled: boolean; + onCursor: CursorHandler; + previousDisabled: boolean; + pageLinks?: string | null; +}; + +/* + HACK: Slight variation of the Pagination + component that allows the parent to control + enabling/disabling the pagination buttons. +*/ +const ScreenshotPagination = ({ + location, + onCursor, + pageLinks, + previousDisabled, + nextDisabled, +}: Props) => { + if (!pageLinks) { + return null; + } + + const path = location.pathname; + const query = location.query; + const links = parseLinkHeader(pageLinks); + + return ( + <Wrapper> + <ButtonBar merged> + <Button + icon={<IconChevron direction="left" size="sm" />} + aria-label={t('Previous')} + size="md" + disabled={previousDisabled} + onClick={() => { + onCursor?.(links.previous?.cursor, path, query, -1); + }} + /> + <Button + icon={<IconChevron direction="right" size="sm" />} + aria-label={t('Next')} + size="md" + disabled={nextDisabled} + onClick={() => { + onCursor?.(links.next?.cursor, path, query, 1); + }} + /> + </ButtonBar> + </Wrapper> + ); +}; + +const Wrapper = styled('div')` + display: flex; + align-items: center; + justify-content: flex-end; + margin: 0; +`; + +export default withRouter(ScreenshotPagination); diff --git a/static/app/views/organizationGroupDetails/groupEventAttachments/groupEventAttachments.tsx b/static/app/views/organizationGroupDetails/groupEventAttachments/groupEventAttachments.tsx index 3b0eee45e3226e..a68cde8f3ebe8f 100644 --- a/static/app/views/organizationGroupDetails/groupEventAttachments/groupEventAttachments.tsx +++ b/static/app/views/organizationGroupDetails/groupEventAttachments/groupEventAttachments.tsx @@ -39,6 +39,8 @@ type State = { eventAttachments?: IssueAttachment[]; } & AsyncComponent['state']; +export const MAX_SCREENSHOTS_PER_PAGE = 6; + class GroupEventAttachments extends AsyncComponent<Props, State> { getDefaultState() { return { @@ -76,7 +78,7 @@ class GroupEventAttachments extends AsyncComponent<Props, State> { ...location.query, types: undefined, // need to explicitly set this to undefined because AsyncComponent adds location query back into the params screenshot: 1, - per_page: 6, + per_page: MAX_SCREENSHOTS_PER_PAGE, }, }, ], @@ -197,6 +199,9 @@ class GroupEventAttachments extends AsyncComponent<Props, State> { projectSlug={projectSlug} groupId={params.groupId} onDelete={this.handleDelete} + pageLinks={this.state.eventAttachmentsPageLinks} + attachments={eventAttachments} + attachmentIndex={index} /> ); })} diff --git a/static/app/views/organizationGroupDetails/groupEventAttachments/screenshotCard.tsx b/static/app/views/organizationGroupDetails/groupEventAttachments/screenshotCard.tsx index 930e15a21e303b..c445d91527b1c2 100644 --- a/static/app/views/organizationGroupDetails/groupEventAttachments/screenshotCard.tsx +++ b/static/app/views/organizationGroupDetails/groupEventAttachments/screenshotCard.tsx @@ -23,11 +23,14 @@ import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAna import useOrganization from 'sentry/utils/useOrganization'; type Props = { + attachmentIndex: number; + attachments: IssueAttachment[]; eventAttachment: IssueAttachment; eventId: string; groupId: string; onDelete: (attachmentId: string) => void; projectSlug: Project['slug']; + pageLinks?: string | null | undefined; }; export function ScreenshotCard({ @@ -36,6 +39,9 @@ export function ScreenshotCard({ eventId, groupId, onDelete, + pageLinks, + attachmentIndex, + attachments, }: Props) { const organization = useOrganization(); const [loadingImage, setLoadingImage] = useState(true); @@ -62,6 +68,11 @@ export function ScreenshotCard({ eventAttachment={eventAttachment} downloadUrl={downloadUrl} onDelete={handleDelete} + pageLinks={pageLinks} + attachments={attachments} + attachmentIndex={attachmentIndex} + groupId={groupId} + enablePagination onDownload={() => trackAdvancedAnalyticsEvent( 'issue_details.attachment_tab.screenshot_modal_download',
3b8609741b1a0db096bb2a7a7d524dc31da14555
2024-09-12 11:34:31
Simon Hellmayr
feat(whats-new): add method to RpcOrganization to retrieve aggregate flags of projects (#77147)
false
add method to RpcOrganization to retrieve aggregate flags of projects (#77147)
feat
diff --git a/src/sentry/organizations/services/organization/impl.py b/src/sentry/organizations/services/organization/impl.py index a6fb610313c75e..2d6d44cd5f6853 100644 --- a/src/sentry/organizations/services/organization/impl.py +++ b/src/sentry/organizations/services/organization/impl.py @@ -1,8 +1,9 @@ from __future__ import annotations from collections.abc import Mapping -from typing import Any +from typing import Any, cast +from django.contrib.postgres.aggregates import BitOr from django.db import models, router, transaction from django.db.models.expressions import CombinedExpression, F from django.dispatch import Signal @@ -30,6 +31,7 @@ from sentry.models.organizationmapping import OrganizationMapping from sentry.models.organizationmember import InviteStatus, OrganizationMember from sentry.models.organizationmemberteam import OrganizationMemberTeam +from sentry.models.project import Project from sentry.models.projectbookmark import ProjectBookmark from sentry.models.recentsearch import RecentSearch from sentry.models.rule import Rule, RuleActivity @@ -72,6 +74,7 @@ from sentry.organizations.services.organization_actions.impl import ( mark_organization_as_pending_deletion_with_outbox_message, ) +from sentry.projects.services.project import RpcProjectFlags from sentry.sentry_apps.services.app import app_service from sentry.silo.safety import unguarded_write from sentry.tasks.auth import email_unlink_notifications @@ -349,6 +352,30 @@ def update_flags(self, *, organization_id: int, flags: RpcOrganizationFlagsUpdat Organization.objects.filter(id=organization_id).update(flags=updates) Organization(id=organization_id).outbox_for_update().save() + def get_aggregate_project_flags(self, *, organization_id: int) -> RpcProjectFlags: + """We need to do some bitfield magic here to convert the aggregate flag into the correct format, because the + original class does not let us instantiate without being tied to the database/django: + 1. Convert the integer into a binary representation + 2. Pad the string with the number of leading zeros so the length of the binary representation lines up with the + number of bits of MAX_BIGINT / the BitField + 3. Reverse the binary representation to correctly assign flags based on the order + 4. Serialize as an RpcProjectFlags object + """ + flag_keys = cast(list[str], Project.flags) + + projects = Project.objects.filter(organization_id=organization_id) + if projects.count() > 0: + aggregate_flag = projects.aggregate(bitor_result=BitOr(F("flags"))) + binary_repr = str(bin(aggregate_flag["bitor_result"]))[2:] + padded_binary_repr = "0" * (64 - len(binary_repr)) + binary_repr + flag_values = list(padded_binary_repr)[::-1] + + else: + flag_values = ["0"] * len(list(flag_keys)) + + flag_dict = dict(zip(flag_keys, flag_values)) + return RpcProjectFlags(**flag_dict) + @staticmethod def _deserialize_member_flags(flags: RpcOrganizationMemberFlags) -> int: return flags_to_bits( diff --git a/src/sentry/organizations/services/organization/model.py b/src/sentry/organizations/services/organization/model.py index 6ccda111bda5bb..418e714cb84a94 100644 --- a/src/sentry/organizations/services/organization/model.py +++ b/src/sentry/organizations/services/organization/model.py @@ -16,7 +16,7 @@ from sentry import roles from sentry.hybridcloud.rpc import RpcModel from sentry.organizations.absolute_url import has_customer_domain, organization_absolute_url -from sentry.projects.services.project import RpcProject +from sentry.projects.services.project import RpcProject, RpcProjectFlags from sentry.roles import team_roles from sentry.roles.manager import TeamRole from sentry.signals import sso_enabled @@ -322,6 +322,11 @@ def default_owner_id(self) -> int | None: self._default_owner_id = owners[0].id return self._default_owner_id + def get_aggregated_project_flags(self, organization_id: int) -> RpcProjectFlags: + from sentry.organizations.services.organization import organization_service + + return organization_service.get_aggregate_project_flags(organization_id=organization_id) + class RpcUserOrganizationContext(RpcModel): """ diff --git a/src/sentry/organizations/services/organization/service.py b/src/sentry/organizations/services/organization/service.py index 62fc77fd42a321..a0e28e24cebdd6 100644 --- a/src/sentry/organizations/services/organization/service.py +++ b/src/sentry/organizations/services/organization/service.py @@ -34,6 +34,7 @@ RpcUserInviteContext, RpcUserOrganizationContext, ) +from sentry.projects.services.project import RpcProjectFlags from sentry.silo.base import SiloMode from sentry.users.services.user.model import RpcUser @@ -165,6 +166,15 @@ def update_flags(self, *, organization_id: int, flags: RpcOrganizationFlagsUpdat """ pass + @regional_rpc_method(resolve=ByOrganizationId()) + @abstractmethod + def get_aggregate_project_flags(self, *, organization_id: int) -> RpcProjectFlags: + """ + Get the union-aggregated project flags of an the organization + + :param organization_id: The organization id + """ + @regional_rpc_method(resolve=ByOrganizationId()) @abstractmethod def check_membership_by_email( diff --git a/src/sentry/projects/services/project/model.py b/src/sentry/projects/services/project/model.py index 852b701353c6ef..ca522e82ff9bdc 100644 --- a/src/sentry/projects/services/project/model.py +++ b/src/sentry/projects/services/project/model.py @@ -21,6 +21,36 @@ class ProjectFilterArgs(TypedDict, total=False): project_ids: list[int] +class RpcProjectFlags(RpcModel): + has_releases: bool + has_issue_alerts_targeting: bool + has_transactions: bool + has_alert_filters: bool + has_sessions: bool + has_profiles: bool + has_replays: bool + has_feedbacks: bool + has_new_feedbacks: bool + spike_protection_error_currently_active: bool + spike_protection_transaction_currently_active: bool + spike_protection_attachment_currently_active: bool + has_minified_stack_trace: bool + has_cron_monitors: bool + has_cron_checkins: bool + has_sourcemaps: bool + has_custom_metrics: bool + has_high_priority_alerts: bool + has_insights_http: bool + has_insights_db: bool + has_insights_assets: bool + has_insights_app_start: bool + has_insights_screen_load: bool + has_insights_vitals: bool + has_insights_caches: bool + has_insights_queues: bool + has_insights_llm_monitoring: bool + + class RpcProject(RpcModel): id: int = -1 slug: str = "" diff --git a/tests/sentry/hybridcloud/test_organization.py b/tests/sentry/hybridcloud/test_organization.py index f19d70ef89fd45..1e64395264b926 100644 --- a/tests/sentry/hybridcloud/test_organization.py +++ b/tests/sentry/hybridcloud/test_organization.py @@ -25,7 +25,7 @@ from sentry.testutils.factories import Factories from sentry.testutils.helpers.task_runner import TaskRunner from sentry.testutils.pytest.fixtures import django_db_all -from sentry.testutils.silo import all_silo_test, assume_test_silo_mode +from sentry.testutils.silo import all_silo_test, assume_test_silo_mode, assume_test_silo_mode_of from sentry.users.models.user import User @@ -360,3 +360,24 @@ def test_send_sso_unlink_emails() -> None: assert len(mail.outbox) == 2 assert "Action Required" in mail.outbox[0].subject assert "Single Sign-On" in mail.outbox[0].body + + +@django_db_all(transaction=True) +@all_silo_test +def test_get_aggregate_project_flags() -> None: + org = Factories.create_organization() + project1 = Factories.create_project(organization_id=org.id, name="test-project-1") + project2 = Factories.create_project(organization_id=org.id, name="test-project-2") + flags = organization_service.get_aggregate_project_flags(organization_id=org.id) + assert flags.has_insights_http is False + assert flags.has_cron_checkins is False + + with assume_test_silo_mode_of(Project): + project1.flags.has_insights_http = True + project1.update(flags=F("flags").bitor(Project.flags.has_insights_http)) + project2.flags.has_insights_http = True + project2.update(flags=F("flags").bitor(Project.flags.has_cron_checkins)) + + flags = organization_service.get_aggregate_project_flags(organization_id=org.id) + assert flags.has_insights_http is True + assert flags.has_cron_checkins is True
2570f565f7390184dc5b8d0d0986f1fc00cceba8
2021-04-01 19:40:50
Tony
feat(trace-view): Add timestamp info to trace view (#24876)
false
Add timestamp info to trace view (#24876)
feat
diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx index a2e5957103c187..054e328ad0b20e 100644 --- a/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx +++ b/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx @@ -8,8 +8,10 @@ import FeatureBadge from 'app/components/featureBadge'; import * as Layout from 'app/components/layouts/thirds'; import LoadingError from 'app/components/loadingError'; import LoadingIndicator from 'app/components/loadingIndicator'; +import TimeSince from 'app/components/timeSince'; import {t, tct, tn} from 'app/locale'; import {Organization} from 'app/types'; +import {getDuration} from 'app/utils/formatters'; import {TraceFullDetailed} from 'app/utils/performance/quickTrace/types'; import {filterTrace} from 'app/utils/performance/quickTrace/utils'; import Breadcrumb from 'app/views/performance/breadcrumb'; @@ -153,6 +155,16 @@ class TraceDetailsContent extends React.Component<Props, State> { traceInfo.relevantProjectsWithErrors.size )} /> + <MetaData + headingText={t('Event Duration')} + tooltipText={t('The time elapsed between the start and end of this trace.')} + bodyText={getDuration( + traceInfo.endTimestamp - traceInfo.startTimestamp, + 2, + true + )} + subtext={<TimeSince date={(traceInfo.endTimestamp || 0) * 1000} />} + /> </TraceDetailHeader> ); }
4c5a824c8d363ace54cbb28293d2ebb25dbd4409
2025-01-18 01:59:26
Nar Saynorath
fix(widget-builder): Release Health fields (#83605)
false
Release Health fields (#83605)
fix
diff --git a/static/app/views/dashboards/widgetBuilder/components/visualize.spec.tsx b/static/app/views/dashboards/widgetBuilder/components/visualize.spec.tsx index 5734345b7a9201..ab3c733e7b0d6f 100644 --- a/static/app/views/dashboards/widgetBuilder/components/visualize.spec.tsx +++ b/static/app/views/dashboards/widgetBuilder/components/visualize.spec.tsx @@ -858,6 +858,30 @@ describe('Visualize', () => { expect(await screen.findByDisplayValue('400')).toBeInTheDocument(); }); + it('restricts deleting the last aggregate in release health widgets', async () => { + render( + <WidgetBuilderProvider> + <Visualize /> + </WidgetBuilderProvider>, + { + organization, + router: RouterFixture({ + location: LocationFixture({ + query: { + dataset: WidgetType.RELEASE, + field: ['crash_free_rate(session)', 'environment'], + }, + }), + }), + } + ); + + const removeButtons = await screen.findAllByRole('button', {name: 'Remove field'}); + expect(removeButtons).toHaveLength(2); + expect(removeButtons[0]).toBeDisabled(); + expect(removeButtons[1]).toBeEnabled(); + }); + describe('spans', () => { beforeEach(() => { jest.mocked(useSpanTags).mockImplementation((type?: 'string' | 'number') => { diff --git a/static/app/views/dashboards/widgetBuilder/components/visualize.tsx b/static/app/views/dashboards/widgetBuilder/components/visualize.tsx index 000a87890bb251..4a72a170429a98 100644 --- a/static/app/views/dashboards/widgetBuilder/components/visualize.tsx +++ b/static/app/views/dashboards/widgetBuilder/components/visualize.tsx @@ -28,6 +28,7 @@ import { import {FieldKind} from 'sentry/utils/fields'; import {decodeScalar} from 'sentry/utils/queryString'; import useLocationQuery from 'sentry/utils/url/useLocationQuery'; +import useApi from 'sentry/utils/useApi'; import useCustomMeasurements from 'sentry/utils/useCustomMeasurements'; import useOrganization from 'sentry/utils/useOrganization'; import useTags from 'sentry/utils/useTags'; @@ -161,6 +162,22 @@ function validateParameter( return false; } +function canDeleteField( + dataset: WidgetType, + selectedFields: QueryFieldValue[], + field: QueryFieldValue +) { + if (dataset === WidgetType.RELEASE) { + // Release Health widgets are required to have at least one aggregate + return ( + selectedFields.filter( + selectedField => selectedField.kind === FieldValueKind.FUNCTION + ).length > 1 || field.kind === FieldValueKind.FIELD + ); + } + return true; +} + interface VisualizeProps { error?: Record<string, any>; setError?: (error: Record<string, any>) => void; @@ -168,6 +185,7 @@ interface VisualizeProps { function Visualize({error, setError}: VisualizeProps) { const organization = useOrganization(); + const api = useApi(); const {state, dispatch} = useWidgetBuilderContext(); let tags = useTags(); const {customMeasurements} = useCustomMeasurements(); @@ -293,6 +311,12 @@ function Visualize({error, setError}: VisualizeProps) { > <Fields> {fields?.map((field, index) => { + const canDelete = canDeleteField( + state.dataset ?? WidgetType.ERRORS, + fields, + field + ); + // Depending on the dataset and the display type, we use different options for // displaying in the column select. // For charts, we show aggregate parameter options for the y-axis as primary options. @@ -319,7 +343,9 @@ function Visualize({error, setError}: VisualizeProps) { label: option.value.meta.name, })); aggregateOptions = - isChartWidget || isBigNumberWidget + isChartWidget || + isBigNumberWidget || + (state.dataset === WidgetType.RELEASE && !canDelete) ? aggregateOptions : [NONE_AGGREGATE, ...aggregateOptions]; @@ -554,13 +580,37 @@ function Visualize({error, setError}: VisualizeProps) { } else { // Handle selecting None so we can select just a field, e.g. for samples // If none is selected, set the field to a field value + + // When selecting None, the next possible columns may be different from the + // possible columns for the previous aggregate. Calculate the valid columns, + // see if the current field's function argument is in the valid columns, and if so, + // set the field to a field value. Otherwise, set the field to the first valid column. + const validColumnFields = Object.values( + datasetConfig.getTableFieldOptions?.( + organization, + tags, + customMeasurements, + api + ) ?? [] + ).filter( + option => + option.value.kind !== FieldValueKind.FUNCTION && + (datasetConfig.filterTableOptions?.(option) ?? true) + ); + const functionArgInValidColumnFields = + ('function' in currentField && + validColumnFields.find( + option => + option.value.meta.name === currentField.function[1] + )) || + undefined; + const validColumn = + functionArgInValidColumnFields?.value.meta.name ?? + validColumnFields?.[0]?.value.meta.name ?? + ''; newFields[index] = { kind: FieldValueKind.FIELD, - field: - 'function' in currentField - ? (currentField.function[1] as string) ?? - columnOptions[0]!.value - : '', + field: validColumn, }; } dispatch({ @@ -635,7 +685,7 @@ function Visualize({error, setError}: VisualizeProps) { borderless icon={<IconDelete />} size="zero" - disabled={fields.length <= 1} + disabled={fields.length <= 1 || !canDelete} onClick={() => { dispatch({ type: updateAction,
cd749418ecf4e2a924848473cb2379aa2d359b86
2022-08-08 14:37:59
Priscila Oliveira
ref(exception-content): Replace Annotated component with _meta object - (#37460)
false
Replace Annotated component with _meta object - (#37460)
ref
diff --git a/static/app/components/events/contexts/user/index.tsx b/static/app/components/events/contexts/user/index.tsx index e2eeb06babaf4a..eec40379748d00 100644 --- a/static/app/components/events/contexts/user/index.tsx +++ b/static/app/components/events/contexts/user/index.tsx @@ -43,7 +43,7 @@ export const userKnownDataValues = [ const userIgnoredDataValues = [UserIgnoredDataType.DATA]; export function UserEventContext({data, event}: Props) { - const meta = event._meta?.contexts?.user ?? {}; + const meta = event._meta?.user ?? event._meta?.contexts?.user ?? {}; return ( <div className="user-widget"> diff --git a/static/app/components/events/interfaces/crashContent/exception/content.tsx b/static/app/components/events/interfaces/crashContent/exception/content.tsx index cf2b3aedf84b48..af5882eaa0d63d 100644 --- a/static/app/components/events/interfaces/crashContent/exception/content.tsx +++ b/static/app/components/events/interfaces/crashContent/exception/content.tsx @@ -1,14 +1,16 @@ import styled from '@emotion/styled'; -import Annotated from 'sentry/components/events/meta/annotated'; +import AnnotatedText from 'sentry/components/events/meta/annotatedText'; +import Tooltip from 'sentry/components/tooltip'; +import {tct} from 'sentry/locale'; import space from 'sentry/styles/space'; import {ExceptionType} from 'sentry/types'; -import {Event} from 'sentry/types/event'; +import {EntryType, Event} from 'sentry/types/event'; import {STACK_TYPE} from 'sentry/types/stacktrace'; +import {defined} from 'sentry/utils'; -import Mechanism from './mechanism'; +import {Mechanism} from './mechanism'; import StackTrace from './stackTrace'; -import ExceptionTitle from './title'; type StackTraceProps = React.ComponentProps<typeof StackTrace>; @@ -24,7 +26,7 @@ type Props = { 'groupingCurrentLevel' | 'hasHierarchicalGrouping' >; -function Content({ +export function Content({ newestFirst, event, stackView, @@ -38,31 +40,50 @@ function Content({ return null; } - const children = values.map((exc, excIdx) => ( - <div key={excIdx} className="exception"> - <ExceptionTitle type={exc.type} exceptionModule={exc?.module} /> - <Annotated object={exc} objectKey="value" required> - {value => <StyledPre className="exc-message">{value}</StyledPre>} - </Annotated> - {exc.mechanism && <Mechanism data={exc.mechanism} />} - <StackTrace - data={ - type === STACK_TYPE.ORIGINAL - ? exc.stacktrace - : exc.rawStacktrace || exc.stacktrace - } - stackView={stackView} - stacktrace={exc.stacktrace} - expandFirstFrame={excIdx === values.length - 1} - platform={platform} - newestFirst={newestFirst} - event={event} - chainedException={values.length > 1} - hasHierarchicalGrouping={hasHierarchicalGrouping} - groupingCurrentLevel={groupingCurrentLevel} - /> - </div> - )); + const exceptionEntryIndex = event.entries.findIndex( + entry => entry.type === EntryType.EXCEPTION + ); + const meta = event._meta?.entries?.[exceptionEntryIndex]?.data?.values; + + const children = values.map((exc, excIdx) => { + return ( + <div key={excIdx} className="exception"> + {defined(exc?.module) ? ( + <Tooltip title={tct('from [exceptionModule]', {exceptionModule: exc?.module})}> + <Title>{exc.type}</Title> + </Tooltip> + ) : ( + <Title>{exc.type}</Title> + )} + <StyledPre className="exc-message"> + {meta?.[excIdx]?.value?.[''] && !exc.value ? ( + <AnnotatedText value={exc.value} meta={meta?.[excIdx]?.value?.['']} /> + ) : ( + exc.value + )} + </StyledPre> + {exc.mechanism && ( + <Mechanism data={exc.mechanism} meta={meta?.[excIdx]?.mechanism} /> + )} + <StackTrace + data={ + type === STACK_TYPE.ORIGINAL + ? exc.stacktrace + : exc.rawStacktrace || exc.stacktrace + } + stackView={stackView} + stacktrace={exc.stacktrace} + expandFirstFrame={excIdx === values.length - 1} + platform={platform} + newestFirst={newestFirst} + event={event} + chainedException={values.length > 1} + hasHierarchicalGrouping={hasHierarchicalGrouping} + groupingCurrentLevel={groupingCurrentLevel} + /> + </div> + ); + }); if (newestFirst) { children.reverse(); @@ -71,9 +92,14 @@ function Content({ return <div>{children}</div>; } -export default Content; - const StyledPre = styled('pre')` margin-bottom: ${space(1)}; margin-top: 0; `; + +const Title = styled('h5')` + margin-bottom: ${space(0.5)}; + overflow-wrap: break-word; + word-wrap: break-word; + word-break: break-word; +`; diff --git a/static/app/components/events/interfaces/crashContent/exception/index.tsx b/static/app/components/events/interfaces/crashContent/exception/index.tsx index 8cd14e6ef9d3cc..4adb63ebfa08af 100644 --- a/static/app/components/events/interfaces/crashContent/exception/index.tsx +++ b/static/app/components/events/interfaces/crashContent/exception/index.tsx @@ -3,7 +3,7 @@ import {ExceptionType, Group, PlatformType, Project} from 'sentry/types'; import {Event} from 'sentry/types/event'; import {STACK_TYPE, STACK_VIEW} from 'sentry/types/stacktrace'; -import Content from './content'; +import {Content} from './content'; import RawContent from './rawContent'; type Props = { diff --git a/static/app/components/events/interfaces/crashContent/exception/mechanism.tsx b/static/app/components/events/interfaces/crashContent/exception/mechanism.tsx index a76dff167bad93..83882230513c8c 100644 --- a/static/app/components/events/interfaces/crashContent/exception/mechanism.tsx +++ b/static/app/components/events/interfaces/crashContent/exception/mechanism.tsx @@ -1,10 +1,10 @@ -import {Component} from 'react'; import {css} from '@emotion/react'; import styled from '@emotion/styled'; import forOwn from 'lodash/forOwn'; import isNil from 'lodash/isNil'; import isObject from 'lodash/isObject'; +import AnnotatedText from 'sentry/components/events/meta/annotatedText'; import {Hovercard} from 'sentry/components/hovercard'; import ExternalLink from 'sentry/components/links/externalLink'; import Pill from 'sentry/components/pill'; @@ -18,76 +18,80 @@ import {Theme} from 'sentry/utils/theme'; type Props = { data: StackTraceMechanism; + meta?: Record<any, any>; }; -class Mechanism extends Component<Props> { - render() { - const mechanism = this.props.data; - const {type, description, help_link, handled, meta = {}, data = {}} = mechanism; - const {errno, signal, mach_exception} = meta; - - const linkElement = help_link && isUrl(help_link) && ( - <StyledExternalLink href={help_link}> - <IconOpen size="xs" /> - </StyledExternalLink> - ); - - const descriptionElement = description && ( - <Hovercard - header={ - <span> - <Details>{t('Details')}</Details> {linkElement} - </span> - } - body={description} - > - <StyledIconInfo size="14px" /> - </Hovercard> - ); - - const pills = [ - <Pill key="mechanism" name="mechanism" value={type || 'unknown'}> - {descriptionElement || linkElement} - </Pill>, - ]; - - if (!isNil(handled)) { - pills.push(<Pill key="handled" name="handled" value={handled} />); - } +export function Mechanism({data: mechanism, meta: mechanismMeta}: Props) { + const {type, description, help_link, handled, meta = {}, data = {}} = mechanism; + const {errno, signal, mach_exception} = meta; + + const linkElement = help_link && isUrl(help_link) && ( + <StyledExternalLink href={help_link}> + <IconOpen size="xs" /> + </StyledExternalLink> + ); + + const descriptionElement = description && ( + <Hovercard + header={ + <span> + <Details>{t('Details')}</Details> {linkElement} + </span> + } + body={description} + > + <StyledIconInfo size="14px" /> + </Hovercard> + ); + + const pills = [ + <Pill key="mechanism" name="mechanism" value={type || 'unknown'}> + {descriptionElement || linkElement} + </Pill>, + ]; + + if (!isNil(handled)) { + pills.push(<Pill key="handled" name="handled" value={handled} />); + } - if (errno) { - const value = errno.name || errno.number; - pills.push(<Pill key="errno" name="errno" value={value} />); - } + if (errno) { + const value = errno.name || errno.number; + pills.push(<Pill key="errno" name="errno" value={value} />); + } - if (mach_exception) { - const value = mach_exception.name || mach_exception.exception; - pills.push(<Pill key="mach" name="mach exception" value={value} />); - } + if (mach_exception) { + const value = mach_exception.name || mach_exception.exception; + pills.push(<Pill key="mach" name="mach exception" value={value} />); + } - if (signal) { - const code = signal.code_name || `${t('code')} ${signal.code}`; - const name = signal.name || signal.number; - const value = isNil(signal.code) ? name : `${name} (${code})`; - pills.push(<Pill key="signal" name="signal" value={value} />); - } + if (signal) { + const code = signal.code_name || `${t('code')} ${signal.code}`; + const name = signal.name || signal.number; + const value = isNil(signal.code) ? name : `${name} (${code})`; + pills.push(<Pill key="signal" name="signal" value={value} />); + } - forOwn(data, (value, key) => { - if (!isObject(value)) { - pills.push(<Pill key={`data:${key}`} name={key} value={value} />); - } - }); + forOwn(data, (value, key) => { + if (!isObject(value)) { + pills.push( + <Pill key={`data:${key}`} name={key}> + {mechanismMeta?.data?.[key]?.[''] && !value ? ( + <AnnotatedText value={value} meta={mechanismMeta?.data?.[key]?.['']} /> + ) : ( + value + )} + </Pill> + ); + } + }); - return ( - <Wrapper> - <StyledPills>{pills}</StyledPills> - </Wrapper> - ); - } + return ( + <Wrapper> + <StyledPills>{pills}</StyledPills> + </Wrapper> + ); } -export default Mechanism; - const Wrapper = styled('div')` margin: ${space(2)} 0; `; diff --git a/static/app/components/events/interfaces/crashContent/exception/title.tsx b/static/app/components/events/interfaces/crashContent/exception/title.tsx deleted file mode 100644 index 04394f12b2dd5e..00000000000000 --- a/static/app/components/events/interfaces/crashContent/exception/title.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import styled from '@emotion/styled'; - -import Tooltip from 'sentry/components/tooltip'; -import {tct} from 'sentry/locale'; -import space from 'sentry/styles/space'; -import {defined} from 'sentry/utils'; - -type Props = { - type: string; - exceptionModule?: string | null; -}; - -const ExceptionTitle = ({type, exceptionModule}: Props) => { - if (defined(exceptionModule)) { - return ( - <Tooltip title={tct('from [exceptionModule]', {exceptionModule})}> - <Title>{type}</Title> - </Tooltip> - ); - } - - return <Title>{type}</Title>; -}; - -export default ExceptionTitle; - -const Title = styled('h5')` - margin-bottom: ${space(0.5)}; - overflow-wrap: break-word; - word-wrap: break-word; - word-break: break-word; -`; diff --git a/static/app/components/events/meta/annotated.tsx b/static/app/components/events/meta/annotated.tsx deleted file mode 100644 index da836ea2c06002..00000000000000 --- a/static/app/components/events/meta/annotated.tsx +++ /dev/null @@ -1,32 +0,0 @@ -import AnnotatedText from 'sentry/components/events/meta/annotatedText'; -import MetaData from 'sentry/components/events/meta/metaData'; -import {isFunction} from 'sentry/utils'; - -type Props<Values> = { - children: (value: string | null | React.ReactNode) => React.ReactNode | string; - object: Values; - objectKey: Extract<keyof Values, string>; - required?: boolean; -}; - -/** - * Returns the value of `object[prop]` and returns an annotated component if - * there is meta data - */ -const Annotated = <Values extends {}>({ - children, - object, - objectKey, - required = false, -}: Props<Values>) => { - return ( - <MetaData object={object} prop={objectKey} required={required}> - {(value, meta) => { - const toBeReturned = <AnnotatedText value={value} meta={meta} />; - return isFunction(children) ? children(toBeReturned) : toBeReturned; - }} - </MetaData> - ); -}; - -export default Annotated; diff --git a/static/app/components/events/meta/metaData.tsx b/static/app/components/events/meta/metaData.tsx deleted file mode 100644 index 9981c3c23311e6..00000000000000 --- a/static/app/components/events/meta/metaData.tsx +++ /dev/null @@ -1,39 +0,0 @@ -import isNil from 'lodash/isNil'; - -import ErrorBoundary from 'sentry/components/errorBoundary'; -import {getMeta} from 'sentry/components/events/meta/metaProxy'; -import {Meta} from 'sentry/types'; - -type Props<Values, K extends Extract<keyof Values, string>> = { - /** - * Render prop that is called with these args: - * value: The actual value, - * meta: metadata object if it exists, otherwise undefined, - */ - children: (value: Values[K], meta?: Meta) => React.ReactNode; - object: Values; - prop: K; - required: boolean; -}; - -/** - * Retrieves metadata from an object (object should be a proxy that - * has been decorated using `app/components/events/meta/metaProxy/withMeta` - */ -const MetaData = <Values extends {}>({ - children, - object, - prop, - required, -}: Props<Values, Extract<keyof Values, string>>) => { - const value = object[prop]; - const meta = getMeta(object, prop); - - if (required && isNil(value) && !meta) { - return null; - } - - return <ErrorBoundary mini>{children(value, meta)}</ErrorBoundary>; -}; - -export default MetaData; diff --git a/static/app/types/stacktrace.tsx b/static/app/types/stacktrace.tsx index 39f68b5a01401d..47f76e7baa37a3 100644 --- a/static/app/types/stacktrace.tsx +++ b/static/app/types/stacktrace.tsx @@ -41,10 +41,10 @@ type MechanismMeta = { export type StackTraceMechanism = { handled: boolean; - synthetic: boolean; type: string; data?: object; description?: string; help_link?: string; meta?: MechanismMeta; + synthetic?: boolean; }; diff --git a/tests/js/spec/components/events/contexts/user/index.spec.tsx b/tests/js/spec/components/events/contexts/user/index.spec.tsx index 5f1f00c00c75ca..91bdc6d0014c1a 100644 --- a/tests/js/spec/components/events/contexts/user/index.spec.tsx +++ b/tests/js/spec/components/events/contexts/user/index.spec.tsx @@ -50,9 +50,7 @@ export const userMetaMockData = { const event = { ...TestStubs.Event(), _meta: { - contexts: { - user: userMetaMockData, - }, + user: userMetaMockData, }, }; diff --git a/tests/js/spec/components/events/interfaces/crashContent/exception/content.spec.tsx b/tests/js/spec/components/events/interfaces/crashContent/exception/content.spec.tsx new file mode 100644 index 00000000000000..70286f67f10da5 --- /dev/null +++ b/tests/js/spec/components/events/interfaces/crashContent/exception/content.spec.tsx @@ -0,0 +1,107 @@ +import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; + +import {Content} from 'sentry/components/events/interfaces/crashContent/exception/content'; +import {EntryType} from 'sentry/types'; +import {STACK_TYPE, STACK_VIEW} from 'sentry/types/stacktrace'; + +describe('Exception Content', function () { + it('display redacted values from exception entry', async function () { + const event = { + ...TestStubs.Event(), + _meta: { + entries: { + 0: { + data: { + values: { + '0': { + mechanism: { + data: { + relevant_address: { + '': { + rem: [['project:3', 's', 0, 0]], + len: 43, + }, + }, + }, + }, + value: { + '': { + rem: [['project:3', 's', 0, 0]], + len: 43, + }, + }, + }, + }, + }, + }, + }, + }, + entries: [ + { + type: EntryType.EXCEPTION, + data: { + values: [ + { + mechanism: { + type: 'celery', + handled: false, + data: {relevant_address: null}, + }, + module: 'sentry.models.organization', + rawStacktrace: null, + stacktrace: { + frames: [ + { + function: null, + colNo: null, + vars: {}, + symbol: null, + module: '<unknown module>', + lineNo: null, + errors: null, + package: null, + absPath: + 'https://sentry.io/hiventy/kraken-prod/issues/438681831/?referrer=slack#', + inApp: false, + instructionAddr: null, + filename: '/hiventy/kraken-prod/issues/438681831/', + platform: null, + context: [], + symbolAddr: null, + }, + ], + framesOmitted: null, + registers: null, + hasSystemFrames: false, + }, + threadId: null, + type: 'Organization.DoesNotExist', + value: null, + }, + ], + }, + }, + ], + }; + + render( + <Content + type={STACK_TYPE.ORIGINAL} + groupingCurrentLevel={0} + hasHierarchicalGrouping + newestFirst + platform="python" + stackView={STACK_VIEW.APP} + event={event} + values={event.entries[0].data.values} + /> + ); + + expect(screen.getAllByText(/redacted/)).toHaveLength(2); + + userEvent.hover(screen.getAllByText(/redacted/)[0]); + expect( + await screen.findByText('Replaced because of PII rule "project:3"') + ).toBeInTheDocument(); // tooltip description + }); +}); diff --git a/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.jsx b/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.jsx deleted file mode 100644 index 807fb7807b1736..00000000000000 --- a/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.jsx +++ /dev/null @@ -1,131 +0,0 @@ -import {render} from 'sentry-test/reactTestingLibrary'; - -import ExceptionMechanism from 'sentry/components/events/interfaces/crashContent/exception/mechanism'; - -describe('ExceptionMechanism', () => { - describe('basic attributes', () => { - it('should render the exception mechanism', () => { - const mechanism = {type: 'generic'}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should render a help_link icon', () => { - const mechanism = {type: 'generic', help_link: 'https://example.org/help'}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should render a description hovercard', () => { - const mechanism = {type: 'generic', description: 'Nothing to see here.'}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should add the help_link to the description hovercard', () => { - const mechanism = { - type: 'generic', - description: 'Nothing to see here.', - help_link: 'https://example.org/help', - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should not add the help_link if not starts with http(s)', () => { - const mechanism = { - type: 'generic', - description: 'Nothing to see here.', - help_link: 'example.org/help', - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should render the handled pill', () => { - const mechanism = {type: 'generic', handled: false}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - }); - - describe('errno meta', () => { - it('should render the errno number', () => { - const mechanism = {type: 'generic', meta: {errno: {number: 7}}}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should prefer the errno name if present', () => { - const mechanism = {type: 'generic', meta: {errno: {number: 7, name: 'E2BIG'}}}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - }); - - describe('mach_exception meta', () => { - it('should render the mach exception number', () => { - const mechanism = { - type: 'generic', - meta: {mach_exception: {exception: 1, subcode: 8, code: 1}}, - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should prefer the exception name if present', () => { - const mechanism = { - type: 'generic', - meta: { - mach_exception: {exception: 1, subcode: 8, code: 1, name: 'EXC_BAD_ACCESS'}, - }, - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - }); - - describe('signal meta', () => { - it('should render the signal number', () => { - const mechanism = {type: 'generic', meta: {signal: {number: 11}}}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should add the signal code if present', () => { - const mechanism = {type: 'generic', meta: {signal: {number: 11, code: 0}}}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should prefer signal and code names if present', () => { - const mechanism = { - type: 'generic', - meta: {signal: {number: 11, code: 0, name: 'SIGSEGV', code_name: 'SEGV_NOOP'}}, - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - }); - - describe('additional data', () => { - it('should render all fields in the data object', () => { - const mechanism = {type: 'generic', data: {relevant_address: '0x1'}}; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - - it('should skip object-like values', () => { - const mechanism = { - type: 'generic', - data: { - a: {x: 11}, - b: [4, 2], - c: new Date(), - }, - }; - const wrapper = render(<ExceptionMechanism data={mechanism} />); - expect(wrapper.container).toSnapshot(); - }); - }); -}); diff --git a/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.tsx b/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.tsx new file mode 100644 index 00000000000000..e218eb3f01f52e --- /dev/null +++ b/tests/js/spec/components/events/interfaces/crashContent/exception/mechanism.spec.tsx @@ -0,0 +1,183 @@ +import {render} from 'sentry-test/reactTestingLibrary'; + +import {Mechanism} from 'sentry/components/events/interfaces/crashContent/exception/mechanism'; +import {StackTraceMechanism} from 'sentry/types/stacktrace'; + +describe('ExceptionMechanism', function () { + describe('basic attributes', function () { + it('should render the exception mechanism', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: true, + }; + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should render a help_link icon', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: true, + help_link: 'https://example.org/help', + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should render a description hovercard', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: true, + description: 'Nothing to see here.', + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should add the help_link to the description hovercard', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: true, + description: 'Nothing to see here.', + help_link: 'https://example.org/help', + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should not add the help_link if not starts with http(s)', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: true, + description: 'Nothing to see here.', + help_link: 'example.org/help', + }; + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should render the handled pill', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + }; + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + }); + + describe('errno meta', function () { + it('should render the errno number', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: {errno: {number: 7}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should prefer the errno name if present', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: {errno: {number: 7, name: 'E2BIG'}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + }); + + describe('mach_exception meta', function () { + it('should render the mach exception number', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: {mach_exception: {exception: 1, subcode: 8, code: 1}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should prefer the exception name if present', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: { + mach_exception: {exception: 1, subcode: 8, code: 1, name: 'EXC_BAD_ACCESS'}, + }, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + }); + + describe('signal meta', function () { + it('should render the signal number', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: {signal: {number: 11}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should add the signal code if present', function () { + const mechanism = { + type: 'generic', + handled: false, + meta: {signal: {number: 11, code: 0}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should prefer signal and code names if present', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + meta: {signal: {number: 11, code: 0, name: 'SIGSEGV', code_name: 'SEGV_NOOP'}}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + }); + + describe('additional data', function () { + it('should render all fields in the data object', function () { + const mechanism = { + type: 'generic', + handled: false, + data: {relevant_address: '0x1'}, + }; + + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + + it('should skip object-like values', function () { + const mechanism: StackTraceMechanism = { + type: 'generic', + handled: false, + data: { + a: {x: 11}, + b: [4, 2], + c: new Date(), + }, + }; + const {container} = render(<Mechanism data={mechanism} />); + expect(container).toSnapshot(); + }); + }); +}); diff --git a/tests/js/spec/components/events/meta/annotated.spec.jsx b/tests/js/spec/components/events/meta/annotated.spec.jsx deleted file mode 100644 index df170a0e3a9cb6..00000000000000 --- a/tests/js/spec/components/events/meta/annotated.spec.jsx +++ /dev/null @@ -1,187 +0,0 @@ -import {mountWithTheme} from 'sentry-test/enzyme'; - -import Annotated from 'sentry/components/events/meta/annotated'; -import {withMeta} from 'sentry/components/events/meta/metaProxy'; - -describe('Annotated', () => { - const mock = jest.fn(() => null); - - const createEvent = (value, {err, rem, chunks} = {}) => - withMeta({ - value, - _meta: { - value: { - '': { - err: err || [], - rem: rem || [], - chunks: chunks || [], - }, - }, - }, - }); - - beforeEach(function () { - mock.mockClear(); - }); - - describe('without meta', () => { - it('renders a string', () => { - const obj = { - value: 'foo', - }; - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: 'foo', - }) - ); - }); - - it('does not error if prop does not exist on object', () => { - const obj = { - value: 'foo', - }; - mountWithTheme(<Annotated object={obj} objectKey="invalid" />); - }); - - it('renders a number', () => { - const obj = { - value: 0, - }; - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: 0, - }) - ); - }); - - it('renders a boolean', () => { - const obj = { - value: false, - }; - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: false, - }) - ); - }); - - it('ignores empty meta data', () => { - const obj = withMeta({ - value: 'foo', - _meta: { - value: { - '': { - err: [], - rem: [], - chunks: [], - }, - }, - }, - }); - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: 'foo', - }) - ); - }); - - it('does not call render prop if required and value is falsy and no meta', () => { - const obj = createEvent(null, {}); - - mountWithTheme( - <Annotated object={obj} objectKey="value" required> - {mock} - </Annotated> - ); - - expect(mock).not.toHaveBeenCalled(); - }); - }); - - describe('with meta', () => { - it('annotates errors', () => { - const meta = {err: ['something']}; - const obj = createEvent('foo', meta); - - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: 'foo', - meta: { - chunks: [], - rem: [], - ...meta, - }, - }) - ); - }); - - it('annotates remarks and chunks', () => { - const meta = {rem: [{type: 't'}], chunks: [{text: 'foo'}]}; - const obj = createEvent('foo', meta); - - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: 'foo', - meta: { - err: [], - ...meta, - }, - }) - ); - }); - - it('annotates redacted text', () => { - const meta = {err: ['something']}; - const obj = createEvent(null, meta); - - mountWithTheme( - <Annotated object={obj} objectKey="value"> - {mock} - </Annotated> - ); - - expect(mock.mock.calls[0][0].props).toEqual( - expect.objectContaining({ - value: null, - meta: { - rem: [], - chunks: [], - ...meta, - }, - }) - ); - }); - }); -}); diff --git a/tests/js/spec/components/events/meta/metaData.spec.jsx b/tests/js/spec/components/events/meta/metaData.spec.jsx deleted file mode 100644 index 22053e93984978..00000000000000 --- a/tests/js/spec/components/events/meta/metaData.spec.jsx +++ /dev/null @@ -1,33 +0,0 @@ -import {mountWithTheme} from 'sentry-test/enzyme'; - -import MetaData from 'sentry/components/events/meta/metaData'; -import {withMeta} from 'sentry/components/events/meta/metaProxy'; - -describe('MetaData', function () { - const exc = TestStubs.ExceptionWithMeta(); - - const proxiedExc = withMeta(exc); - - it('can get meta data', function () { - const renderProp = jest.fn(() => null); - mountWithTheme( - <MetaData object={proxiedExc.exception.values[0]} prop="value"> - {renderProp} - </MetaData> - ); - - expect(renderProp).toHaveBeenCalledWith( - 'python err A949AE01EBB07300D62AE0178F0944DD21F8C98C err', - { - len: 29, - rem: [['device_id', 'p', 11, 51]], - } - ); - }); - - it('has the right value', function () { - expect(proxiedExc.exception.values[0].value).toBe( - 'python err A949AE01EBB07300D62AE0178F0944DD21F8C98C err' - ); - }); -});
e8b37184072d80ec8f708cc11695f9193a42841a
2022-03-01 21:14:58
Tony Xiao
chore(profiling): Use Pagefilter[datetime] on profiling chart (#32129)
false
Use Pagefilter[datetime] on profiling chart (#32129)
chore
diff --git a/static/app/views/profiling/content.tsx b/static/app/views/profiling/content.tsx index 59f4deb8ebf0e3..4ce542564c9730 100644 --- a/static/app/views/profiling/content.tsx +++ b/static/app/views/profiling/content.tsx @@ -7,7 +7,6 @@ import Alert from 'sentry/components/alert'; import * as Layout from 'sentry/components/layouts/thirds'; import NoProjectMessage from 'sentry/components/noProjectMessage'; import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container'; -import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; import PageHeading from 'sentry/components/pageHeading'; import Pagination from 'sentry/components/pagination'; import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle'; @@ -53,7 +52,6 @@ function ProfilingContent({location, selection}: ProfilingContentProps) { const [traces, setTraces] = useState<Trace[]>([]); const [pageLinks, setPageLinks] = useState<string | null>(null); const organization = useOrganization(); - const dateSelection = normalizeDateTimeParams(location.query); const cursor = decodeScalar(location.query.cursor); const api = useApi(); @@ -93,7 +91,14 @@ function ProfilingContent({location, selection}: ProfilingContentProps) { </Alert> )} <ProfilingScatterChart - {...dateSelection} + datetime={ + selection?.datetime ?? { + start: null, + end: null, + period: null, + utc: null, + } + } traces={traces} isLoading={requestState === 'loading'} /> diff --git a/static/app/views/profiling/landing/profilingScatterChart.tsx b/static/app/views/profiling/landing/profilingScatterChart.tsx index 92c3b27600b657..086b5d2ce68791 100644 --- a/static/app/views/profiling/landing/profilingScatterChart.tsx +++ b/static/app/views/profiling/landing/profilingScatterChart.tsx @@ -19,7 +19,7 @@ import {getSeriesSelection} from 'sentry/components/charts/utils'; import {Panel} from 'sentry/components/panels'; import {t} from 'sentry/locale'; import ConfigStore from 'sentry/stores/configStore'; -import {Organization, Project} from 'sentry/types'; +import {Organization, PageFilters, Project} from 'sentry/types'; import {Series} from 'sentry/types/echarts'; import {Trace} from 'sentry/types/profiling/core'; import {defined} from 'sentry/utils'; @@ -33,24 +33,17 @@ import {generateFlamegraphRoute} from '../routes'; import {COLOR_ENCODINGS, getColorEncodingFromLocation} from '../utils'; interface ProfilingScatterChartProps extends WithRouterProps { + datetime: PageFilters['datetime']; isLoading: boolean; - location: Location; traces: Trace[]; - end?: string; - start?: string; - statsPeriod?: string | null; - utc?: string; } function ProfilingScatterChart({ router, location, - traces, + datetime, isLoading, - start, - end, - statsPeriod, - utc, + traces, }: ProfilingScatterChartProps) { const organization = useOrganization(); const {projects} = useProjects(); @@ -112,10 +105,10 @@ function ProfilingScatterChart({ <ChartContainer> <ChartZoom router={router} - period={statsPeriod} - start={start} - end={end} - utc={utc === 'true'} + period={datetime.period} + start={datetime.start} + end={datetime.end} + utc={datetime.utc} > {zoomRenderProps => { return (
e1d2a6ff7ab54a7b8f2efd74ef413e36e40e5c64
2024-04-03 19:50:48
Tony Xiao
chore(onboarding): Update flutter onboarding to include profiling (#68099)
false
Update flutter onboarding to include profiling (#68099)
chore
diff --git a/static/app/components/onboarding/productSelection.tsx b/static/app/components/onboarding/productSelection.tsx index b4494bf2b2bfb2..ec4ee53537d2db 100644 --- a/static/app/components/onboarding/productSelection.tsx +++ b/static/app/components/onboarding/productSelection.tsx @@ -77,6 +77,7 @@ function getDisabledProducts(organization: Organization): DisabledProducts { export const platformProductAvailability = { android: [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING], bun: [ProductSolution.PERFORMANCE_MONITORING], + flutter: [ProductSolution.PERFORMANCE_MONITORING, ProductSolution.PROFILING], kotlin: [ProductSolution.PERFORMANCE_MONITORING], java: [ProductSolution.PERFORMANCE_MONITORING], 'java-spring-boot': [ProductSolution.PERFORMANCE_MONITORING], diff --git a/static/app/gettingStartedDocs/flutter/flutter.spec.tsx b/static/app/gettingStartedDocs/flutter/flutter.spec.tsx index 7c9f819be0353f..1e693a474f2863 100644 --- a/static/app/gettingStartedDocs/flutter/flutter.spec.tsx +++ b/static/app/gettingStartedDocs/flutter/flutter.spec.tsx @@ -2,10 +2,12 @@ import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboa import {screen} from 'sentry-test/reactTestingLibrary'; import {textWithMarkupMatcher} from 'sentry-test/utils'; +import {ProductSolution} from 'sentry/components/onboarding/productSelection'; + import docs from './flutter'; describe('flutter onboarding docs', function () { - it('renders docs correctly', async function () { + it('renders errors onboarding docs correctly', async function () { renderWithOnboardingLayout(docs, { releaseRegistry: { 'sentry.dart.flutter': { @@ -24,4 +26,49 @@ describe('flutter onboarding docs', function () { await screen.findByText(textWithMarkupMatcher(/sentry_flutter: \^1\.99\.9/)) ).toBeInTheDocument(); }); + + it('renders performance onboarding docs correctly', async function () { + renderWithOnboardingLayout(docs, { + releaseRegistry: { + 'sentry.dart.flutter': { + version: '1.99.9', + }, + }, + selectedProducts: [ProductSolution.PERFORMANCE_MONITORING], + }); + + expect( + await screen.findByText(textWithMarkupMatcher(/options.tracesSampleRate/)) + ).toBeInTheDocument(); + expect( + await screen.findByText( + textWithMarkupMatcher( + /You'll be able to monitor the performance of your app using the SDK./ + ) + ) + ).toBeInTheDocument(); + }); + + it('renders profiling onboarding docs correctly', async function () { + renderWithOnboardingLayout(docs, { + releaseRegistry: { + 'sentry.dart.flutter': { + version: '1.99.9', + }, + }, + selectedProducts: [ + ProductSolution.PERFORMANCE_MONITORING, + ProductSolution.PROFILING, + ], + }); + + expect( + await screen.findByText(textWithMarkupMatcher(/options.profilesSampleRate/)) + ).toBeInTheDocument(); + expect( + await screen.findByText( + textWithMarkupMatcher(/Flutter Profiling alpha is available/) + ) + ).toBeInTheDocument(); + }); }); diff --git a/static/app/gettingStartedDocs/flutter/flutter.tsx b/static/app/gettingStartedDocs/flutter/flutter.tsx index 924c9467524008..954621ca9254fd 100644 --- a/static/app/gettingStartedDocs/flutter/flutter.tsx +++ b/static/app/gettingStartedDocs/flutter/flutter.tsx @@ -22,10 +22,21 @@ import 'package:sentry_flutter/sentry_flutter.dart'; Future<void> main() async { await SentryFlutter.init( (options) { - options.dsn = '${params.dsn}'; + options.dsn = '${params.dsn}';${ + params.isPerformanceSelected + ? ` // Set tracesSampleRate to 1.0 to capture 100% of transactions for performance monitoring. // We recommend adjusting this value in production. - options.tracesSampleRate = 1.0; + options.tracesSampleRate = 1.0;` + : '' + }${ + params.isProfilingSelected + ? ` + // The sampling rate for profiling is relative to tracesSampleRate + // Setting to 1.0 will profile 100% of sampled transactions: + options.profilesSampleRate = 1.0;` + : '' + } }, appRunner: () => runApp(MyApp()), ); @@ -100,6 +111,15 @@ const onboarding: OnboardingConfig = { sentryFlutter: <code />, }), configurations: [ + ...(params.isProfilingSelected + ? [ + { + description: t( + 'Flutter Profiling alpha is available for iOS and macOS since SDK version 7.12.0.' + ), + }, + ] + : []), { language: 'dart', code: getConfigureSnippet(params), @@ -117,7 +137,7 @@ const onboarding: OnboardingConfig = { ], }, ], - verify: () => [ + verify: (params: Params) => [ { type: StepType.VERIFY, description: t( @@ -136,26 +156,30 @@ const onboarding: OnboardingConfig = { }, ], }, - { - title: t('Performance'), - description: t( - "You'll be able to monitor the performance of your app using the SDK. For example:" - ), - configurations: [ - { - language: 'dart', - code: getPerformanceSnippet(), - additionalInfo: tct( - 'To learn more about the API and automatic instrumentations, check out the [perfDocs: performance documentation].', - { - perfDocs: ( - <ExternalLink href="https://docs.sentry.io/platforms/flutter/performance/instrumentation/" /> - ), - } - ), - }, - ], - }, + ...(params.isPerformanceSelected + ? [ + { + title: t('Performance'), + description: t( + "You'll be able to monitor the performance of your app using the SDK. For example:" + ), + configurations: [ + { + language: 'dart', + code: getPerformanceSnippet(), + additionalInfo: tct( + 'To learn more about the API and automatic instrumentations, check out the [perfDocs: performance documentation].', + { + perfDocs: ( + <ExternalLink href="https://docs.sentry.io/platforms/flutter/performance/instrumentation/" /> + ), + } + ), + }, + ], + }, + ] + : []), ], nextSteps: () => [ {
8d015d32a0f92ac46b03c118c08fc2a1c2c9bd54
2021-02-11 23:48:07
Scott Cooper
feat(workflow): Track referrer in inbox out events (WOR-603) (#23785)
false
Track referrer in inbox out events (WOR-603) (#23785)
feat
diff --git a/src/sentry/analytics/events/inbox_out.py b/src/sentry/analytics/events/inbox_out.py index 28823c8c287566..3783fa665cac9e 100644 --- a/src/sentry/analytics/events/inbox_out.py +++ b/src/sentry/analytics/events/inbox_out.py @@ -11,6 +11,7 @@ class InboxOutEvent(analytics.Event): analytics.Attribute("group_id"), analytics.Attribute("action"), analytics.Attribute("inbox_in_ts", type=int), + analytics.Attribute("referrer", required=False), ) diff --git a/src/sentry/api/helpers/group_index.py b/src/sentry/api/helpers/group_index.py index 2f39a3ea004653..a46e008e13a307 100644 --- a/src/sentry/api/helpers/group_index.py +++ b/src/sentry/api/helpers/group_index.py @@ -1000,7 +1000,10 @@ def update_groups(request, projects, organization_id, search_fn, has_inbox=False elif not inbox: for group in group_list: remove_group_from_inbox( - group, action=GroupInboxRemoveAction.MARK_REVIEWED, user=acting_user + group, + action=GroupInboxRemoveAction.MARK_REVIEWED, + user=acting_user, + referrer=request.META.get("HTTP_REFERER"), ) issue_mark_reviewed.send_robust( project=project, diff --git a/src/sentry/models/groupinbox.py b/src/sentry/models/groupinbox.py index 7ddd7b79c96fa7..b14bfc34a363f1 100644 --- a/src/sentry/models/groupinbox.py +++ b/src/sentry/models/groupinbox.py @@ -91,7 +91,7 @@ def add_group_to_inbox(group, reason, reason_details=None): return group_inbox -def remove_group_from_inbox(group, action=None, user=None): +def remove_group_from_inbox(group, action=None, user=None, referrer=None): try: group_inbox = GroupInbox.objects.get(group=group) group_inbox.delete() @@ -112,6 +112,7 @@ def remove_group_from_inbox(group, action=None, user=None): sender="remove_group_from_inbox", action=action.value, inbox_date_added=group_inbox.date_added, + referrer=referrer, ) except GroupInbox.DoesNotExist: pass diff --git a/src/sentry/receivers/features.py b/src/sentry/receivers/features.py index 87a55b8e4c3e88..30eb0d8a0d568e 100644 --- a/src/sentry/receivers/features.py +++ b/src/sentry/receivers/features.py @@ -475,7 +475,7 @@ def record_inbox_in(project, user, group, reason, **kwargs): @inbox_out.connect(weak=False) -def record_inbox_out(project, user, group, action, inbox_date_added, **kwargs): +def record_inbox_out(project, user, group, action, inbox_date_added, referrer, **kwargs): if user and user.is_authenticated(): user_id = default_user_id = user.id else: @@ -490,6 +490,7 @@ def record_inbox_out(project, user, group, action, inbox_date_added, **kwargs): group_id=group.id, action=action, inbox_in_ts=int(time.mktime(inbox_date_added.timetuple())), + referrer=referrer, ) diff --git a/src/sentry/signals.py b/src/sentry/signals.py index 0fb134d1dd0f4d..4f866b9c5a37f5 100644 --- a/src/sentry/signals.py +++ b/src/sentry/signals.py @@ -95,7 +95,9 @@ def send_robust(self, sender, **named): issue_unignored = BetterSignal(providing_args=["project", "user", "group", "transition_type"]) issue_mark_reviewed = BetterSignal(providing_args=["project", "user", "group"]) inbox_in = BetterSignal(providing_args=["project", "user", "group", "reason"]) -inbox_out = BetterSignal(providing_args=["project", "user", "group", "action", "inbox_date_added"]) +inbox_out = BetterSignal( + providing_args=["project", "user", "group", "action", "inbox_date_added", "referrer"] +) terms_accepted = BetterSignal(providing_args=["organization", "user", "ip_address"]) team_created = BetterSignal(providing_args=["organization", "user", "team"]) diff --git a/tests/sentry/receivers/test_signals.py b/tests/sentry/receivers/test_signals.py index 55729a2a2dfb2e..febc24bebbbe5c 100644 --- a/tests/sentry/receivers/test_signals.py +++ b/tests/sentry/receivers/test_signals.py @@ -65,5 +65,6 @@ def test_inbox_out(self, mock_record): sender="test_inbox_out", action="mark_reviewed", inbox_date_added=group_inbox.date_added, + referrer="https://sentry.io/inbox", ) assert mock_record.called
2975a322a2466ffd7e7b0a569d54eab93f7ae9e7
2022-09-06 16:16:14
Matej Minar
feat(sampling): Add more platforms to the allowlist (#38453)
false
Add more platforms to the allowlist (#38453)
feat
diff --git a/src/sentry/api/endpoints/organization_dynamic_sampling_sdk_versions.py b/src/sentry/api/endpoints/organization_dynamic_sampling_sdk_versions.py index ecfe765acbf98f..306d377a4b0136 100644 --- a/src/sentry/api/endpoints/organization_dynamic_sampling_sdk_versions.py +++ b/src/sentry/api/endpoints/organization_dynamic_sampling_sdk_versions.py @@ -29,13 +29,15 @@ "sentry.javascript.nextjs", # Next.js "sentry.javascript.remix", # RemixJS "sentry.javascript.node", # Node, Express, koa + "sentry.javascript.react-native", # React Native "sentry.javascript.serverless", # AWS Lambda Node "sentry.python", # python, django, flask, FastAPI, Starlette, Bottle, Celery, pyramid, rq "sentry.python.serverless", # AWS Lambda "sentry.cocoa", # iOS - "sentry.java.android", # Android ) ) +# We want sentry.java.android, sentry.java.android.timber, and all others to match +ALLOWED_SDK_NAMES_PREFIXES = frozenset(("sentry.java.android",)) class QueryBoundsException(Exception): @@ -192,7 +194,9 @@ def get(self, request: Request, organization) -> Response: project_to_sdk_version_to_info_dict: Dict[Any, Any] = {} for row in data: project = row["project"] - sdk_name = row["sdk.name"] + sdk_name = ( + row["sdk.name"] or "" + ) # Defaulting to string just to be sure because we are later using startswith sdk_version = row["sdk.version"] # Filter 1: Discard any sdk name that accounts less than or equal to the value # `SDK_NAME_FILTER_THRESHOLD` of total count per project @@ -210,7 +214,8 @@ def get(self, request: Request, organization) -> Response: "latestSDKVersion": sdk_version, "isSendingSampleRate": bool(row[f"equation|{avg_sample_rate_equation}"]), "isSendingSource": bool(row[f"equation|{avg_transaction_source_equation}"]), - "isSupportedPlatform": (sdk_name in ALLOWED_SDK_NAMES), + "isSupportedPlatform": (sdk_name in ALLOWED_SDK_NAMES) + or (sdk_name.startswith(tuple(ALLOWED_SDK_NAMES_PREFIXES))), } # Essentially for each project, we fetch all the SDK versions from the previously diff --git a/tests/sentry/api/endpoints/test_organization_dynamic_sampling_sdk_versions.py b/tests/sentry/api/endpoints/test_organization_dynamic_sampling_sdk_versions.py index 96618aa2998b92..c0754f5130916f 100644 --- a/tests/sentry/api/endpoints/test_organization_dynamic_sampling_sdk_versions.py +++ b/tests/sentry/api/endpoints/test_organization_dynamic_sampling_sdk_versions.py @@ -174,6 +174,17 @@ def mocked_discover_query(): 'count_if(transaction.source, notEquals, "")': 0, "count()": 1, }, + # project: timber + { + "sdk.version": "6.4.1", + "sdk.name": "sentry.java.android.timber", + "project": "timber", + 'equation|count_if(trace.client_sample_rate, notEquals, "") / count()': 1.0, + 'count_if(trace.client_sample_rate, notEquals, "")': 7, + 'equation|count_if(transaction.source, notEquals, "") / count()': 1.0, + 'count_if(transaction.source, notEquals, "")': 5, + "count()": 23, + }, # project: dummy { "sdk.version": "7.1.4", @@ -325,6 +336,14 @@ def test_successful_response(self, mock_query): "isSendingSource": False, "isSupportedPlatform": True, }, + { + "project": "timber", + "latestSDKName": "sentry.java.android.timber", + "latestSDKVersion": "6.4.1", + "isSendingSampleRate": True, + "isSendingSource": True, + "isSupportedPlatform": True, + }, { "project": "dummy", "latestSDKName": "sentry.unknown",
b029c7e07f8ff1e6c7adff1331dd890ef0648771
2023-12-13 02:21:42
Tony Xiao
fix(stats-detector): Lazily create redis client (#61627)
false
Lazily create redis client (#61627)
fix
diff --git a/src/sentry/statistical_detectors/redis.py b/src/sentry/statistical_detectors/redis.py index 8fb3de8d3d2ed2..e8ca560f740c88 100644 --- a/src/sentry/statistical_detectors/redis.py +++ b/src/sentry/statistical_detectors/redis.py @@ -26,7 +26,16 @@ def __init__( ): self.detector_type = detector_type self.ttl = ttl - self.client = self.get_redis_client() if client is None else client + self._client: RedisCluster | StrictRedis | None = None + + @property + def client( + self, + client: RedisCluster | StrictRedis | None = None, + ): + if self._client is None: + self._client = self.get_redis_client() if client is None else client + return self._client def bulk_read_states( self, payloads: List[DetectorPayload]
cba6db7cf5ac2d53ef664088842df269bbcb6677
2020-05-18 20:35:32
Markus Unterwaditzer
ref: Clean up apm sample rate configuration (#18881)
false
Clean up apm sample rate configuration (#18881)
ref
diff --git a/src/sentry/api/endpoints/relay_projectconfigs.py b/src/sentry/api/endpoints/relay_projectconfigs.py index 7ee340a3e6a696..a90e70216e7044 100644 --- a/src/sentry/api/endpoints/relay_projectconfigs.py +++ b/src/sentry/api/endpoints/relay_projectconfigs.py @@ -1,9 +1,12 @@ from __future__ import absolute_import +import random import logging import six from rest_framework.response import Response +from django.conf import settings + from sentry_sdk import Hub from sentry_sdk.tracing import Span @@ -20,13 +23,17 @@ PROJECT_CONFIG_SIZE_THRESHOLD = 10000 +def _sample_apm(): + return random.random() < getattr(settings, "SENTRY_RELAY_ENDPOINT_APM_SAMPLING", 0) + + class RelayProjectConfigsEndpoint(Endpoint): authentication_classes = (RelayAuthentication,) permission_classes = (RelayPermission,) def post(self, request): with Hub.current.start_span( - Span(op="http.server", transaction="RelayProjectConfigsEndpoint", sampled=True) + Span(op="http.server", transaction="RelayProjectConfigsEndpoint", sampled=_sample_apm()) ): return self._post(request) diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index c49d20a2480193..f83e7fd5e4e3e9 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -945,14 +945,25 @@ def create_partitioned_queues(name): # Configuration for JavaScript's whitelistUrls - defaults to ALLOWED_HOSTS SENTRY_FRONTEND_WHITELIST_URLS = None -# Sample rate for Sentry transactions +# ---- +# APM config +# ---- + +# sample rate for transactions initiated from the frontend SENTRY_APM_SAMPLING = 0 # Sample rate for symbolicate_event task transactions -SENTRY_SYMBOLICATE_EVENT_APM_SAMPLING = 0.1 +SENTRY_SYMBOLICATE_EVENT_APM_SAMPLING = 0 # Sample rate for the process_event task transactions -SENTRY_PROCESS_EVENT_APM_SAMPLING = 0.01 +SENTRY_PROCESS_EVENT_APM_SAMPLING = 0 + +# sample rate for the relay projectconfig endpoint +SENTRY_RELAY_ENDPOINT_APM_SAMPLING = 0 + +# ---- +# end APM config +# ---- # DSN to use for Sentry monitors SENTRY_MONITOR_DSN = None
51981dc5869d4c818103e7afb648be687b6080f8
2021-10-11 12:46:29
Matej Minar
fix(ui): Do not show threshold type on session alerts (#29206)
false
Do not show threshold type on session alerts (#29206)
fix
diff --git a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx index 56f5c54903c258..6fc3f3a3aef1db 100644 --- a/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx +++ b/static/app/views/alerts/incidentRules/ruleConditionsForm.tsx @@ -148,6 +148,7 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { comparisonDelta, onComparisonDeltaChange, onComparisonTypeChange, + dataset, } = this.props; const {environments} = this.state; @@ -282,9 +283,9 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { : model.setValue('aggregate', DEFAULT_AGGREGATE); // set the value of the dataset and event type from data source - const {dataset, eventTypes} = + const {dataset: datasetFromDataSource, eventTypes} = DATA_SOURCE_TO_SET_AND_EVENT_TYPES[optionValue] ?? {}; - model.setValue('dataset', dataset); + model.setValue('dataset', datasetFromDataSource); model.setValue('eventTypes', eventTypes); }} options={dataSourceOptions} @@ -337,27 +338,29 @@ class RuleConditionsForm extends React.PureComponent<Props, State> { {...(this.searchSupportedTags ? {supportedTags: this.searchSupportedTags} : {})} - hasRecentSearches={this.props.dataset !== Dataset.SESSIONS} + hasRecentSearches={dataset !== Dataset.SESSIONS} /> </SearchContainer> )} </FormField> </FormRow> - <Feature features={['organizations:change-alerts']} organization={organization}> - <StyledListItem>{t('Select threshold type')}</StyledListItem> - <FormRow> - <RadioGroup - style={{flex: 1}} - choices={[ - [AlertRuleComparisonType.COUNT, 'Count'], - [AlertRuleComparisonType.CHANGE, 'Percent Change'], - ]} - value={comparisonType} - label={t('Threshold Type')} - onChange={onComparisonTypeChange} - /> - </FormRow> - </Feature> + {dataset !== Dataset.SESSIONS && ( + <Feature features={['organizations:change-alerts']} organization={organization}> + <StyledListItem>{t('Select threshold type')}</StyledListItem> + <FormRow> + <RadioGroup + style={{flex: 1}} + choices={[ + [AlertRuleComparisonType.COUNT, 'Count'], + [AlertRuleComparisonType.CHANGE, 'Percent Change'], + ]} + value={comparisonType} + label={t('Threshold Type')} + onChange={onComparisonTypeChange} + /> + </FormRow> + </Feature> + )} <StyledListItem> <StyledListTitle> <div>{intervalLabelText}</div>
7470f34da05b5aeffb8089fb8b69c7eee6c7ca9c
2018-04-17 03:46:58
Brett Hoerner
feat: Support searches that combine Environment and Release:latest (#8054)
false
Support searches that combine Environment and Release:latest (#8054)
feat
diff --git a/src/sentry/search/base.py b/src/sentry/search/base.py index 12e5cac15e454b..c8147290e7bd48 100644 --- a/src/sentry/search/base.py +++ b/src/sentry/search/base.py @@ -11,7 +11,6 @@ from sentry.utils.services import Service ANY = object() -EMPTY = object() class SearchBackend(Service): diff --git a/src/sentry/search/django/backend.py b/src/sentry/search/django/backend.py index a83669fb6ac7e7..1ef8817f8b2336 100644 --- a/src/sentry/search/django/backend.py +++ b/src/sentry/search/django/backend.py @@ -183,6 +183,26 @@ def assigned_to_filter(queryset, user, project): ) +def get_latest_release(project, environment): + from sentry.models import Release + + release_qs = Release.objects.filter( + organization_id=project.organization_id, + projects=project, + ) + + if environment is not None: + release_qs = release_qs.filter( + releaseprojectenvironment__environment__id=environment.id + ) + + return release_qs.extra(select={ + 'sort': 'COALESCE(date_released, date_added)', + }).order_by('-sort').values_list( + 'version', flat=True + )[:1].get() + + class DjangoSearchBackend(SearchBackend): def query(self, project, tags=None, environment=None, sort_by='date', limit=100, cursor=None, count_hits=False, paginator_options=None, **parameters): @@ -195,6 +215,16 @@ def query(self, project, tags=None, environment=None, sort_by='date', limit=100, if tags is None: tags = {} + try: + if tags.get('sentry:release') == 'latest': + tags['sentry:release'] = get_latest_release(project, environment) + + if parameters.get('first_release') == 'latest': + parameters['first_release'] = get_latest_release(project, environment) + except Release.DoesNotExist: + # no matches could possibly be found from this point on + return Paginator(Group.objects.none()).get_result() + group_queryset = QuerySetBuilder({ 'query': CallbackCondition( lambda queryset, query: queryset.filter( diff --git a/src/sentry/search/utils.py b/src/sentry/search/utils.py index 611d89c626e681..c49d94bce5dade 100644 --- a/src/sentry/search/utils.py +++ b/src/sentry/search/utils.py @@ -8,8 +8,8 @@ from django.utils import timezone from sentry.constants import STATUS_CHOICES -from sentry.models import EventUser, Release, User -from sentry.search.base import ANY, EMPTY +from sentry.models import EventUser, User +from sentry.search.base import ANY from sentry.utils.auth import find_users @@ -17,22 +17,6 @@ class InvalidQuery(Exception): pass -def parse_release(project, value): - # TODO(dcramer): add environment support - if value == 'latest': - value = Release.objects.filter( - organization_id=project.organization_id, - projects=project, - ).extra(select={ - 'sort': 'COALESCE(date_released, date_added)', - }).order_by('-sort').values_list( - 'version', flat=True - ).first() - if value is None: - return EMPTY - return value - - def get_user_tag(project, key, value): # TODO(dcramer): do something with case of multiple matches try: @@ -364,9 +348,9 @@ def parse_query(project, query, user): elif key == 'subscribed': results['subscribed_by'] = parse_user_value(value, user) elif key in ('first-release', 'firstRelease'): - results['first_release'] = parse_release(project, value) + results['first_release'] = value elif key == 'release': - results['tags']['sentry:release'] = parse_release(project, value) + results['tags']['sentry:release'] = value elif key == 'dist': results['tags']['sentry:dist'] = value elif key == 'user': diff --git a/src/sentry/tagstore/legacy/backend.py b/src/sentry/tagstore/legacy/backend.py index 5fa9f9ab1ce35a..9156de76a585cb 100644 --- a/src/sentry/tagstore/legacy/backend.py +++ b/src/sentry/tagstore/legacy/backend.py @@ -573,7 +573,7 @@ def get_group_tag_values_for_users(self, event_users, limit=100): def get_group_ids_for_search_filter( self, project_id, environment_id, tags, candidates=None, limit=1000): - from sentry.search.base import ANY, EMPTY + from sentry.search.base import ANY # Django doesnt support union, so we limit results and try to find # reasonable matches @@ -587,10 +587,7 @@ def get_group_ids_for_search_filter( # for each remaining tag, find matches contained in our # existing set, pruning it down each iteration for k, v in tag_lookups: - if v is EMPTY: - return None - - elif v != ANY: + if v != ANY: base_qs = GroupTagValue.objects.filter( key=k, value=v, diff --git a/src/sentry/tagstore/snuba/backend.py b/src/sentry/tagstore/snuba/backend.py index fec3ca8a133dab..b7b4b3097df155 100644 --- a/src/sentry/tagstore/snuba/backend.py +++ b/src/sentry/tagstore/snuba/backend.py @@ -390,12 +390,9 @@ def get_groups_user_counts(self, project_id, group_ids, environment_id): # Search def get_group_ids_for_search_filter(self, project_id, environment_id, tags): - from sentry.search.base import ANY, EMPTY + from sentry.search.base import ANY + start, end = self.get_time_range() - # Any EMPTY value means there can be no results for this query so - # return an empty list immediately. - if any(val == EMPTY for _, val in six.iteritems(tags)): - return [] filters = { 'environment': [environment_id], diff --git a/src/sentry/tagstore/v2/backend.py b/src/sentry/tagstore/v2/backend.py index 0e6fea2c63dbf8..b929eb002afc4b 100644 --- a/src/sentry/tagstore/v2/backend.py +++ b/src/sentry/tagstore/v2/backend.py @@ -796,7 +796,7 @@ def get_group_tag_values_for_users(self, event_users, limit=100): def get_group_ids_for_search_filter( self, project_id, environment_id, tags, candidates=None, limit=1000): - from sentry.search.base import ANY, EMPTY + from sentry.search.base import ANY # Django doesnt support union, so we limit results and try to find # reasonable matches @@ -810,10 +810,7 @@ def get_group_ids_for_search_filter( # for each remaining tag, find matches contained in our # existing set, pruning it down each iteration for k, v in tag_lookups: - if v is EMPTY: - return None - - elif v != ANY: + if v != ANY: base_qs = GroupTagValue.objects.filter( project_id=project_id, _key__key=k, diff --git a/tests/sentry/search/django/tests.py b/tests/sentry/search/django/tests.py index 00b008b9d36043..9aad17d779dcbd 100644 --- a/tests/sentry/search/django/tests.py +++ b/tests/sentry/search/django/tests.py @@ -11,10 +11,11 @@ from sentry import tagstore from sentry.event_manager import ScoreClause from sentry.models import ( - Environment, Event, GroupAssignee, GroupBookmark, GroupEnvironment, GroupStatus, GroupSubscription + Environment, Event, GroupAssignee, GroupBookmark, GroupEnvironment, GroupStatus, + GroupSubscription, Release, ReleaseEnvironment, ReleaseProjectEnvironment ) from sentry.search.base import ANY -from sentry.search.django.backend import DjangoSearchBackend +from sentry.search.django.backend import DjangoSearchBackend, get_latest_release from sentry.tagstore.v2.backend import AGGREGATE_ENVIRONMENT_ID from sentry.testutils import TestCase @@ -711,3 +712,58 @@ def test_subscribed_by_with_environment(self): subscribed_by=self.user, ) assert set(results) == set([]) + + def test_parse_release_latest(self): + with pytest.raises(Release.DoesNotExist): + # no releases exist period + environment = None + result = get_latest_release(self.project, environment) + + old = Release.objects.create( + organization_id=self.project.organization_id, + version='old' + ) + old.add_project(self.project) + + new_date = old.date_added + timedelta(minutes=1) + new = Release.objects.create( + version='new-but-in-environment', + organization_id=self.project.organization_id, + date_released=new_date, + ) + new.add_project(self.project) + ReleaseEnvironment.get_or_create( + project=self.project, + release=new, + environment=self.environment, + datetime=new_date, + ) + ReleaseProjectEnvironment.get_or_create( + project=self.project, + release=new, + environment=self.environment, + datetime=new_date, + ) + + newest = Release.objects.create( + version='newest-overall', + organization_id=self.project.organization_id, + date_released=old.date_added + timedelta(minutes=5), + ) + newest.add_project(self.project) + + # latest overall (no environment filter) + environment = None + result = get_latest_release(self.project, environment) + assert result == newest.version + + # latest in environment + environment = self.environment + result = get_latest_release(self.project, environment) + assert result == new.version + + with pytest.raises(Release.DoesNotExist): + # environment with no releases + environment = self.create_environment() + result = get_latest_release(self.project, environment) + assert result == new.version diff --git a/tests/sentry/search/test_utils.py b/tests/sentry/search/test_utils.py index 1b1a9f6b740295..022dac62fd46c1 100644 --- a/tests/sentry/search/test_utils.py +++ b/tests/sentry/search/test_utils.py @@ -5,7 +5,7 @@ from datetime import datetime, timedelta from django.utils import timezone -from sentry.models import EventUser, GroupStatus, Release +from sentry.models import EventUser, GroupStatus from sentry.testutils import TestCase from sentry.search.base import ANY from sentry.search.utils import parse_query, get_numeric_field_value @@ -287,19 +287,6 @@ def test_first_release(self): result = self.parse_query('first-release:bar') assert result == {'first_release': 'bar', 'tags': {}, 'query': ''} - def test_first_release_latest(self): - old = Release.objects.create(organization_id=self.project.organization_id, version='a') - old.add_project(self.project) - new = Release.objects.create( - version='b', - organization_id=self.project.organization_id, - date_released=old.date_added + timedelta(minutes=1), - ) - new.add_project(self.project) - - result = self.parse_query('first-release:latest') - assert result == {'tags': {}, 'first_release': new.version, 'query': ''} - def test_release(self): result = self.parse_query('release:bar') assert result == {'tags': {'sentry:release': 'bar'}, 'query': ''} @@ -308,19 +295,6 @@ def test_dist(self): result = self.parse_query('dist:123') assert result == {'tags': {'sentry:dist': '123'}, 'query': ''} - def test_release_latest(self): - old = Release.objects.create(organization_id=self.project.organization_id, version='a') - old.add_project(self.project) - new = Release.objects.create( - version='b', - organization_id=self.project.organization_id, - date_released=old.date_added + timedelta(minutes=1), - ) - new.add_project(self.project) - - result = self.parse_query('release:latest') - assert result == {'tags': {'sentry:release': new.version}, 'query': ''} - def test_padded_spacing(self): result = self.parse_query('release:bar foo bar') assert result == {'tags': {'sentry:release': 'bar'}, 'query': 'foo bar'}
707f353d2d1933fbf951478c414838f9e5956b38
2025-01-01 05:24:03
Hubert Deng
chore(devservices): Bump devservices to 1.0.8 (#82799)
false
Bump devservices to 1.0.8 (#82799)
chore
diff --git a/requirements-dev-frozen.txt b/requirements-dev-frozen.txt index 89a84c5b48d333..18227cc5072c89 100644 --- a/requirements-dev-frozen.txt +++ b/requirements-dev-frozen.txt @@ -37,7 +37,7 @@ cryptography==43.0.1 cssselect==1.0.3 cssutils==2.9.0 datadog==0.49.1 -devservices==1.0.7 +devservices==1.0.8 distlib==0.3.8 distro==1.8.0 django==5.1.4 diff --git a/requirements-dev.txt b/requirements-dev.txt index 5293cdc9317b38..0748993df7b1a1 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,7 +1,7 @@ --index-url https://pypi.devinfra.sentry.io/simple sentry-devenv>=1.14.2 -devservices>=1.0.7 +devservices>=1.0.8 covdefaults>=2.3.0 sentry-covdefaults-disable-branch-coverage>=1.0.2
54e6ac495c67d71226e285e5add883e9570900f7
2020-07-01 21:48:20
Billy Vong
build(github): Add a GitHub action to diff PR snapshots against main branch (#19585)
false
Add a GitHub action to diff PR snapshots against main branch (#19585)
build
diff --git a/.github/workflows/acceptance.yml b/.github/workflows/acceptance.yml index c7b176ce92a82c..1863738e7eb028 100644 --- a/.github/workflows/acceptance.yml +++ b/.github/workflows/acceptance.yml @@ -125,6 +125,7 @@ jobs: echo "::set-output name=python-version::2.7" echo "::set-output name=matrix-instance-number::$(($MATRIX_INSTANCE+1))" + # yarn cache - uses: actions/cache@v1 id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`) @@ -204,3 +205,33 @@ jobs: with: name: visual-snapshots path: .artifacts/visual-snapshots + + + visual-diff: + needs: acceptance + runs-on: ubuntu-16.04 + + steps: + - name: Download base snapshots + uses: actions/download-artifact@v2 + with: + name: visual-snapshots + path: .artifacts/visual-snapshots + + - name: Diff snapshots + if: ${{ github.ref != 'refs/heads/master' }} + id: visual-snapshots-diff + uses: getsentry/action-visual-snapshot@v1 + with: + githubToken: ${{ secrets.GITHUB_TOKEN }} + snapshot-path: .artifacts/visual-snapshots + diff-path: .artifacts/visual-snapshots-diff + gcs-bucket: 'sentry-visual-snapshots' + gcp-service-account-key: ${{ secrets.SNAPSHOT_GOOGLE_SERVICE_ACCOUNT_KEY }} + + - name: Save diffed snapshots + if: always() + uses: actions/upload-artifact@v2 + with: + name: visual-snapshots-diff + path: ${{ steps.visual-snapshots-diff.outputs.diff-path }} diff --git a/src/sentry/static/sentry/app/styles/global.tsx b/src/sentry/static/sentry/app/styles/global.tsx index 0eca7d06e0e8ae..865aefb389aa98 100644 --- a/src/sentry/static/sentry/app/styles/global.tsx +++ b/src/sentry/static/sentry/app/styles/global.tsx @@ -1,3 +1,4 @@ +/* global process */ import React from 'react'; import {Global, css} from '@emotion/core'; @@ -13,6 +14,26 @@ const styles = (theme: Theme) => css` abbr { border-bottom: 1px dotted ${theme.gray500}; } + + /** + * TODO: This should apply to the prefer-reduced-motion media query + * + * See https://web.dev/prefers-reduced-motion/ + */ + ${process.env.IS_CI && + css` + *, + ::before, + ::after { + animation-delay: -1ms !important; + animation-duration: 0ms !important; + animation-iteration-count: 1 !important; + background-attachment: initial !important; + scroll-behavior: auto !important; + transition-duration: 0s !important; + transition-delay: 0s !important; + } + `} `; /**
24f4a83ca31a70bc396a5f5311fe5b8cde20cd1b
2024-01-02 19:00:59
Riccardo Busetti
feat(ddm): Extend billing consumer to update flag on project model (#61351)
false
Extend billing consumer to update flag on project model (#61351)
feat
diff --git a/src/sentry/ingest/billing_metrics_consumer.py b/src/sentry/ingest/billing_metrics_consumer.py index 1def7d66bf54a6..75cef1b5b5aef4 100644 --- a/src/sentry/ingest/billing_metrics_consumer.py +++ b/src/sentry/ingest/billing_metrics_consumer.py @@ -1,6 +1,6 @@ import logging from datetime import datetime, timezone -from typing import Any, Mapping, Optional, TypedDict, Union, cast +from typing import Any, Mapping, Optional, cast from arroyo.backends.kafka import KafkaPayload from arroyo.processing.strategies import ( @@ -9,17 +9,29 @@ ProcessingStrategyFactory, ) from arroyo.types import Commit, Message, Partition -from typing_extensions import NotRequired +from django.core.cache import cache +from django.db.models import F +from sentry_kafka_schemas.schema_types.snuba_generic_metrics_v1 import GenericMetric from sentry.constants import DataCategory +from sentry.models.project import Project from sentry.sentry_metrics.indexer.strings import SHARED_TAG_STRINGS, TRANSACTION_METRICS_NAMES from sentry.sentry_metrics.use_case_id_registry import UseCaseID from sentry.sentry_metrics.utils import reverse_resolve_tag_value +from sentry.snuba.metrics import parse_mri +from sentry.snuba.metrics.naming_layer.mri import is_custom_metric from sentry.utils import json from sentry.utils.outcomes import Outcome, track_outcome logger = logging.getLogger(__name__) +# 7 days of TTL. +CACHE_TTL_IN_SECONDS = 60 * 60 * 24 * 7 + + +def _get_project_flag_updated_cache_key(org_id: int, project_id: int) -> str: + return f"has-custom-metrics-flag-updated:{org_id}:{project_id}" + class BillingMetricsConsumerStrategyFactory(ProcessingStrategyFactory[KafkaPayload]): def create_with_partitions( @@ -30,22 +42,6 @@ def create_with_partitions( return BillingTxCountMetricConsumerStrategy(CommitOffsets(commit)) -class MetricsBucket(TypedDict): - """ - Metrics bucket as decoded from kafka. - - Only defines the fields that are relevant for this consumer.""" - - org_id: int - project_id: int - metric_id: int - timestamp: int - value: Any - tags: Union[Mapping[str, str], Mapping[str, int]] - # not used here but allows us to use the TypedDict for assignments - type: NotRequired[str] - - class BillingTxCountMetricConsumerStrategy(ProcessingStrategy[KafkaPayload]): """A metrics consumer that generates a billing outcome for each processed transaction, processing a bucket at a time. The transaction count is @@ -74,26 +70,30 @@ def submit(self, message: Message[KafkaPayload]) -> None: assert not self.__closed payload = self._get_payload(message) + self._produce_billing_outcomes(payload) + self._flag_metric_received_for_project(payload) + self.__next_step.submit(message) - def _get_payload(self, message: Message[KafkaPayload]) -> MetricsBucket: + def _get_payload(self, message: Message[KafkaPayload]) -> GenericMetric: payload = json.loads(message.payload.value.decode("utf-8"), use_rapid_json=True) - return cast(MetricsBucket, payload) + return cast(GenericMetric, payload) - def _count_processed_items(self, bucket_payload: MetricsBucket) -> Mapping[DataCategory, int]: - if bucket_payload["metric_id"] != self.metric_id: + def _count_processed_items(self, generic_metric: GenericMetric) -> Mapping[DataCategory, int]: + if generic_metric["metric_id"] != self.metric_id: return {} - value = bucket_payload["value"] + + value = generic_metric["value"] try: - quantity = max(int(value), 0) + quantity = max(int(value), 0) # type:ignore except TypeError: # Unexpected value type for this metric ID, skip. return {} items = {DataCategory.TRANSACTION: quantity} - if self._has_profile(bucket_payload): + if self._has_profile(generic_metric): # The bucket is tagged with the "has_profile" tag, # so we also count the quantity of this bucket towards profiles. # This assumes a "1 to 0..1" relationship between transactions and profiles. @@ -101,18 +101,20 @@ def _count_processed_items(self, bucket_payload: MetricsBucket) -> Mapping[DataC return items - def _has_profile(self, bucket: MetricsBucket) -> bool: + def _has_profile(self, generic_metric: GenericMetric) -> bool: return bool( - (tag_value := bucket["tags"].get(self.profile_tag_key)) + (tag_value := generic_metric["tags"].get(self.profile_tag_key)) and "true" - == reverse_resolve_tag_value(UseCaseID.TRANSACTIONS, bucket["org_id"], tag_value) + == reverse_resolve_tag_value( + UseCaseID.TRANSACTIONS, generic_metric["org_id"], tag_value + ) ) - def _produce_billing_outcomes(self, payload: MetricsBucket) -> None: - for category, quantity in self._count_processed_items(payload).items(): + def _produce_billing_outcomes(self, generic_metric: GenericMetric) -> None: + for category, quantity in self._count_processed_items(generic_metric).items(): self._produce_billing_outcome( - org_id=payload["org_id"], - project_id=payload["project_id"], + org_id=generic_metric["org_id"], + project_id=generic_metric["project_id"], category=category, quantity=quantity, ) @@ -141,5 +143,40 @@ def _produce_billing_outcome( quantity=quantity, ) + def _flag_metric_received_for_project(self, generic_metric: GenericMetric) -> None: + try: + org_id = generic_metric["org_id"] + project_id = generic_metric["project_id"] + metric_mri = self._resolve(generic_metric["mapping_meta"], generic_metric["metric_id"]) + + parsed_mri = parse_mri(metric_mri) + # If the metric is not custom, we don't want to perform any work. + if parsed_mri is None or not is_custom_metric(parsed_mri): + return + + # If the cache key is there, we don't want to load the project at all. + cache_key = _get_project_flag_updated_cache_key(org_id, project_id) + if cache.get(cache_key) is not None: + return + + project = Project.objects.get_from_cache(id=project_id) + if not project.flags.has_custom_metrics: + # We assume that the flag update is reflected in the cache, so that upcoming calls will get the up-to- + # date project with the `has_custom_metrics` flag set to true. + project.update(flags=F("flags").bitor(Project.flags.has_custom_metrics)) + + # If we are here, it means that we received a custom metric, and we didn't have it reflected in the cache, + # so we update the cache. + cache.set(cache_key, "1", CACHE_TTL_IN_SECONDS) + except Project.DoesNotExist: + pass + + def _resolve(self, mapping_meta: Mapping[str, Any], indexed_value: int) -> Optional[str]: + for _, inner_meta in mapping_meta.items(): + if (string_value := inner_meta.get(str(indexed_value))) is not None: + return string_value + + return None + def join(self, timeout: Optional[float] = None) -> None: self.__next_step.join(timeout) diff --git a/tests/sentry/ingest/billing_metrics_consumer/test_billing_metrics_consumer_kafka.py b/tests/sentry/ingest/billing_metrics_consumer/test_billing_metrics_consumer_kafka.py index 29023ab6d9f424..8a9d7a0b4654bd 100644 --- a/tests/sentry/ingest/billing_metrics_consumer/test_billing_metrics_consumer_kafka.py +++ b/tests/sentry/ingest/billing_metrics_consumer/test_billing_metrics_consumer_kafka.py @@ -1,120 +1,177 @@ from __future__ import annotations from datetime import datetime, timezone +from typing import cast from unittest import mock from arroyo.backends.kafka import KafkaPayload from arroyo.types import BrokerValue, Message, Partition, Topic +from django.core.cache import cache +from sentry_kafka_schemas.schema_types.snuba_generic_metrics_v1 import GenericMetric from sentry.constants import DataCategory from sentry.ingest.billing_metrics_consumer import ( BillingTxCountMetricConsumerStrategy, - MetricsBucket, + _get_project_flag_updated_cache_key, ) +from sentry.models.project import Project +from sentry.sentry_metrics import indexer from sentry.sentry_metrics.indexer.strings import SHARED_TAG_STRINGS, TRANSACTION_METRICS_NAMES -from sentry.testutils.helpers.datetime import freeze_time +from sentry.sentry_metrics.use_case_id_registry import UseCaseID +from sentry.testutils.pytest.fixtures import django_db_all from sentry.utils import json from sentry.utils.outcomes import Outcome +@django_db_all @mock.patch("sentry.ingest.billing_metrics_consumer.track_outcome") -@freeze_time("1985-10-26 21:00:00") -def test_outcomes_consumed(track_outcome): +def test_outcomes_consumed(track_outcome, factories): # Based on test_ingest_consumer_kafka.py - topic = Topic("snuba-generic-metrics") # NOTE: For a more realistic test, the usage metric is always emitted # alongside the transaction duration metric. Formerly, the consumer used the # duration metric to generate outcomes. + organization = factories.create_organization() + project_1 = factories.create_project(organization=organization) + project_2 = factories.create_project(organization=organization) + missing_project_id = 2 + + transaction_usage_mri = "c:transactions/usage@none" + transaction_usage_id = TRANSACTION_METRICS_NAMES["c:transactions/usage@none"] + + transaction_duration_mri = "d:transactions/duration@millisecond" + transaction_duration_id = TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"] + + counter_custom_metric_mri = "c:custom/user_click@none" + counter_custom_metric_id = cast( + int, indexer.record(UseCaseID.CUSTOM, organization.id, counter_custom_metric_mri) + ) + + distribution_custom_metric_mri = "d:custom/page_load@ms" + distribution_custom_metric_id = cast( + int, indexer.record(UseCaseID.CUSTOM, organization.id, distribution_custom_metric_mri) + ) + empty_tags: dict[str, str] = {} profile_tags: dict[str, str] = {str(SHARED_TAG_STRINGS["has_profile"]): "true"} - buckets: list[MetricsBucket] = [ + generic_metrics: list[GenericMetric] = [ { # Counter metric with wrong ID will not generate an outcome - "metric_id": 123, + "mapping_meta": {"c": {str(counter_custom_metric_id): counter_custom_metric_mri}}, + "metric_id": counter_custom_metric_id, "type": "c", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_1.id, "timestamp": 123, "value": 123.4, "tags": empty_tags, + "use_case_id": "custom", + "retention_days": 90, }, { # Distribution metric with wrong ID will not generate an outcome - "metric_id": 123, + "mapping_meta": { + "c": {str(distribution_custom_metric_id): distribution_custom_metric_mri} + }, + "metric_id": distribution_custom_metric_id, "type": "d", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_1.id, "timestamp": 123456, "value": [1.0, 2.0], "tags": empty_tags, + "use_case_id": "custom", + "retention_days": 90, }, # Usage with `0.0` will not generate an outcome # NOTE: Should not be emitted by Relay anyway { - "metric_id": TRANSACTION_METRICS_NAMES["c:transactions/usage@none"], + "mapping_meta": {"c": {str(transaction_usage_id): transaction_usage_mri}}, + "metric_id": transaction_usage_id, "type": "c", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_1.id, "timestamp": 123456, "value": 0.0, "tags": empty_tags, + "use_case_id": "transactions", + "retention_days": 90, }, { - "metric_id": TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"], + "mapping_meta": {"c": {str(transaction_duration_id): transaction_duration_mri}}, + "metric_id": transaction_duration_id, "type": "d", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_1.id, "timestamp": 123456, "value": [], "tags": empty_tags, + "use_case_id": "transactions", + "retention_days": 90, }, # Usage buckets with positive counter emit an outcome { - "metric_id": TRANSACTION_METRICS_NAMES["c:transactions/usage@none"], + "mapping_meta": {"c": {str(transaction_usage_id): transaction_usage_mri}}, + "metric_id": transaction_usage_id, "type": "c", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_2.id, "timestamp": 123456, "value": 3.0, "tags": empty_tags, + "use_case_id": "transactions", + "retention_days": 90, }, { - "metric_id": TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"], + "mapping_meta": {"c": {str(transaction_duration_id): transaction_duration_mri}}, + "metric_id": transaction_duration_id, "type": "d", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_2.id, "timestamp": 123456, "value": [1.0, 2.0, 3.0], "tags": empty_tags, + "use_case_id": "transactions", + "retention_days": 90, }, { # Another bucket to introduce some noise - "metric_id": 123, + "mapping_meta": { + "c": {str(distribution_custom_metric_id): distribution_custom_metric_mri} + }, + "metric_id": distribution_custom_metric_id, "type": "c", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": project_2.id, "timestamp": 123456, "value": 123.4, "tags": empty_tags, + "use_case_id": "custom", + "retention_days": 90, }, # Bucket with profiles { - "metric_id": TRANSACTION_METRICS_NAMES["c:transactions/usage@none"], + "mapping_meta": {"c": {str(transaction_usage_id): transaction_usage_mri}}, + "metric_id": transaction_usage_id, "type": "c", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": missing_project_id, "timestamp": 123456, "value": 1.0, "tags": profile_tags, + "use_case_id": "transactions", + "retention_days": 90, }, { - "metric_id": TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"], + "mapping_meta": {"c": {str(transaction_duration_id): transaction_duration_mri}}, + "metric_id": transaction_duration_id, "type": "d", - "org_id": 1, - "project_id": 2, + "org_id": organization.id, + "project_id": missing_project_id, "timestamp": 123456, "value": [4.0], "tags": profile_tags, + "use_case_id": "transactions", + "retention_days": 90, }, ] @@ -126,10 +183,10 @@ def test_outcomes_consumed(track_outcome): generate_kafka_message_counter = 0 - def generate_kafka_message(bucket: MetricsBucket) -> Message[KafkaPayload]: + def generate_kafka_message(generic_metric: GenericMetric) -> Message[KafkaPayload]: nonlocal generate_kafka_message_counter - encoded = json.dumps(bucket).encode() + encoded = json.dumps(generic_metric).encode() payload = KafkaPayload(key=None, value=encoded, headers=[]) message = Message( BrokerValue( @@ -147,55 +204,70 @@ def generate_kafka_message(bucket: MetricsBucket) -> Message[KafkaPayload]: strategy.poll() strategy.poll() assert track_outcome.call_count == 0 - for i, bucket in enumerate(buckets): + for i, generic_metric in enumerate(generic_metrics): strategy.poll() assert next_step.submit.call_count == i - strategy.submit(generate_kafka_message(bucket)) + strategy.submit(generate_kafka_message(generic_metric)) # commit is called for every message, and later debounced by arroyo's policy assert next_step.submit.call_count == (i + 1) if i < 4: assert track_outcome.call_count == 0 + assert Project.objects.get(id=project_1.id).flags.has_custom_metrics elif i < 7: assert track_outcome.mock_calls == [ mock.call( - org_id=1, - project_id=2, + org_id=organization.id, + project_id=project_2.id, key_id=None, outcome=Outcome.ACCEPTED, reason=None, - timestamp=datetime(1985, 10, 26, 21, 00, 00, tzinfo=timezone.utc), + timestamp=mock.ANY, event_id=None, category=DataCategory.TRANSACTION, quantity=3, ), ] + # We have a custom metric in the 7th element, thus we expect that before that we have no flag set and after + # that yes. + if i == 6: + assert Project.objects.get(id=project_2.id).flags.has_custom_metrics + else: + assert not Project.objects.get(id=project_2.id).flags.has_custom_metrics else: assert track_outcome.mock_calls[1:] == [ mock.call( - org_id=1, - project_id=2, + org_id=organization.id, + project_id=missing_project_id, key_id=None, outcome=Outcome.ACCEPTED, reason=None, - timestamp=datetime(1985, 10, 26, 21, 00, 00, tzinfo=timezone.utc), + timestamp=mock.ANY, event_id=None, category=DataCategory.TRANSACTION, quantity=1, ), mock.call( - org_id=1, - project_id=2, + org_id=organization.id, + project_id=missing_project_id, key_id=None, outcome=Outcome.ACCEPTED, reason=None, - timestamp=datetime(1985, 10, 26, 21, 00, 00, tzinfo=timezone.utc), + timestamp=mock.ANY, event_id=None, category=DataCategory.PROFILE, quantity=1, ), ] + # We double-check that the project does not exist. + assert not Project.objects.filter(id=2).exists() assert next_step.submit.call_count == 9 strategy.join() assert next_step.join.call_count == 1 + + assert cache.get(_get_project_flag_updated_cache_key(organization.id, project_1.id)) is not None + assert cache.get(_get_project_flag_updated_cache_key(organization.id, project_2.id)) is not None + assert ( + cache.get(_get_project_flag_updated_cache_key(organization.id, missing_project_id)) is None + )
388e943eeb19d19b218162cd18457314156df5c5
2022-05-26 00:07:56
Vladan Paunovic
chore: bump Sentry SDK to 7.0.0-rc.0 (#35009)
false
bump Sentry SDK to 7.0.0-rc.0 (#35009)
chore
diff --git a/package.json b/package.json index 63436412ed4964..c7adebf4faba3b 100644 --- a/package.json +++ b/package.json @@ -23,13 +23,13 @@ "@emotion/styled": "^11.3.0", "@popperjs/core": "^2.11.5", "@sentry-internal/global-search": "^0.0.43", - "@sentry/integrations": "7.0.0-beta.2", - "@sentry/node": "7.0.0-beta.2", - "@sentry/react": "7.0.0-beta.2", + "@sentry/integrations": "7.0.0-rc.0", + "@sentry/node": "7.0.0-rc.0", + "@sentry/react": "7.0.0-rc.0", "@sentry/release-parser": "^1.3.0", "@sentry/rrweb": "^0.3.1", - "@sentry/tracing": "7.0.0-beta.2", - "@sentry/utils": "7.0.0-beta.2", + "@sentry/tracing": "7.0.0-rc.0", + "@sentry/utils": "7.0.0-rc.0", "@testing-library/jest-dom": "^5.16.1", "@testing-library/react": "^12.1.2", "@testing-library/react-hooks": "^8.0.0", diff --git a/yarn.lock b/yarn.lock index ad1fb4db9cee9f..e7536a98b35489 100644 --- a/yarn.lock +++ b/yarn.lock @@ -2874,67 +2874,67 @@ htmlparser2 "^4.1.0" title-case "^3.0.2" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-7.0.0-beta.2.tgz#41d0b36d1f5e25176938c48d8c940ac1e8db7711" - integrity sha512-Z1mHL5+CsbTRu7ivU+8H8j1ZBmvYkzZuh/dGHFubw1rOe6WxO2+rBbvC2H82VMOI/aX8nCQWMA33LTosLoGKGA== - dependencies: - "@sentry/core" "7.0.0-beta.2" - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/browser/-/browser-7.0.0-rc.0.tgz#c6fab6693a2e100268c855cea4f4abc2d421c9fa" + integrity sha512-6YVxKfDEMwvDrq59ZHS7m3lxya8E45DWkA1gcVxsDIz89XKhLNc4eDvsjc07G1NjzQ+YHqWFevcHoEweobtdLw== + dependencies: + "@sentry/core" "7.0.0-rc.0" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/core/-/core-7.0.0-beta.2.tgz#e16e47790523522963f0b96656b0817fbecaf204" - integrity sha512-trJa+P/w5g4P2/rVDXC9ZAwx8rH/Q354n2COO8DQcHMG2jLA1B8c7GxiO0zq+Uoe+xz8lq+hVAkC0aLgtRia9w== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/core/-/core-7.0.0-rc.0.tgz#f3984d8fd4302ee6ada45ab667165b5adcc482f6" + integrity sha512-uoYH2O9groVZU9IelT8mLC/qFpHQxpqUGu+Ei21bB4P4nUJYjL4GpWV0DsgWuZp4zk4BoTn7V98pc19p5M3aWg== dependencies: - "@sentry/hub" "7.0.0-beta.2" - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/hub" "7.0.0-rc.0" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-7.0.0-beta.2.tgz#6eb172f89ae28a032d1ed6a779899fc9478cd0b7" - integrity sha512-SRXKzTrZneBXmHLGLHU+Pw+7tRtltUDzK7NIlHuzZGh8HQf8i0v/wDmorNaVL+GkkggzutH/Bdf8bXuHkjtzNg== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/hub/-/hub-7.0.0-rc.0.tgz#d6575061847619a0913dc034ec1f564be539ea7f" + integrity sha512-8OZbfCO4W10VUC/S8SFiEeI3EmigDRJc7gSn1kpNfI0jQIRsl8ivuJTuyhSrsQiEXt0c0wxXn3Wy8+FLLycgYg== dependencies: - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/integrations/-/integrations-7.0.0-beta.2.tgz#101d63d52b3fde3f528d866211b4278e166fe5a5" - integrity sha512-n7f67O4v/dwIFERFbmqKh5MNHUqO3k+fyj9Bof5YkVcPQM3YNhIERiYg6onvmyOZ4gX/rmSWgXTqr3skI0Hx6g== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/integrations/-/integrations-7.0.0-rc.0.tgz#fd44bb52a3684e0c896e69f659201035f09582c3" + integrity sha512-yvXGVPHtMXIomsMintgMi0urWzX6zDKbwlt7dB7TZ1IJnOWf7n4PD3lEQ8BtMxE8cXJ1zmS9CkdoYaWqp4RzCw== dependencies: - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" localforage "^1.8.1" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/node/-/node-7.0.0-beta.2.tgz#99f42648de08d17e9f111aee44503e581caa4de4" - integrity sha512-2cPlziqb2+WeAMyXQSv+XfRQNB9f4jRmXvcn7sNplUgtPPFTbjjizHHhYvw7grCjwYkZDGhKSJDxEqTfQZXcaA== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/node/-/node-7.0.0-rc.0.tgz#8d02c5a71f704487449a7b2dd4ece6769e77552d" + integrity sha512-flf5mmBipyWNFyxt1HOUIMVpacWIDmQgjmfKQ1VL+IApJN71F0JWL10Llqe7NXY5McqlmQy8489c4m8Hps5XzA== dependencies: - "@sentry/core" "7.0.0-beta.2" - "@sentry/hub" "7.0.0-beta.2" - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/core" "7.0.0-rc.0" + "@sentry/hub" "7.0.0-rc.0" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" cookie "^0.4.1" https-proxy-agent "^5.0.0" lru_map "^0.3.3" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/react/-/react-7.0.0-beta.2.tgz#d71bdfec1b7422a1499751b84d6f71213e1a63ef" - integrity sha512-Cns8RQ4mMeFLbeh0jzQALVFJgE6cqAbfKMsKvKxoJsf+SkHLbozjkMkLEmEnVMDOpeIAgsM34yURkEEh2fM51g== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/react/-/react-7.0.0-rc.0.tgz#9ce24524e351284ce1f3469c7d5afdc8f410dd1c" + integrity sha512-Qc6Xxh7JXcqakU26DCDJeDQZPOVp00HgaI+jl/5U8KrUvnc9WCAvDskWBlIfnO/SDEx7m5eYuX5NN3UDnQwt1w== dependencies: - "@sentry/browser" "7.0.0-beta.2" - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/browser" "7.0.0-rc.0" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" hoist-non-react-statics "^3.3.2" tslib "^1.9.3" @@ -2948,27 +2948,27 @@ resolved "https://registry.yarnpkg.com/@sentry/rrweb/-/rrweb-0.3.1.tgz#a0f7496e086a30679d7af227d62ab76cfd5ed934" integrity sha512-AJIy2yqjtgpcow3L1gyxxr6x+rqLN9HXMlsNNmLeUKlPBxaSMP47lM6aexI3V+XkKnRmOW05H21cLimyuM+59Q== -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/tracing/-/tracing-7.0.0-beta.2.tgz#2e948da3d8d73913490901293db82a2b69ba05d5" - integrity sha512-e8jlC6y1Se4K8MdFigucA27TTriuCNACQOzkfN3YLgYJii2AB+Iz9XUAmfpmpzpejGEKC7IaaaBrbRPnUc3hxQ== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/tracing/-/tracing-7.0.0-rc.0.tgz#616e8f8c101106f273a0ac4a5f8f80affe767db3" + integrity sha512-1o3XgVkfUBy1bpG2g3p+0orwhFgThwc8Om6nWeto3mVsVGZzmxGi3SmvxG5JZ0I0j0nMAOL9O+N9c5LWxBeSrA== dependencies: - "@sentry/hub" "7.0.0-beta.2" - "@sentry/types" "7.0.0-beta.2" - "@sentry/utils" "7.0.0-beta.2" + "@sentry/hub" "7.0.0-rc.0" + "@sentry/types" "7.0.0-rc.0" + "@sentry/utils" "7.0.0-rc.0" tslib "^1.9.3" -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/types/-/types-7.0.0-beta.2.tgz#f836784930b5cb64ba13602f0ec3e6110f430c9c" - integrity sha512-nU9BT/kBy6sQfq0M0s+LzGrjg8ELofOubhPwX1RZC0cPsUzKbFPCISnikbQJDC7J0Kg0TpQrGs/FP0mFxp3ItA== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/types/-/types-7.0.0-rc.0.tgz#ec6e6503d76157bc35df625dc514aecbd890ee91" + integrity sha512-6TGWcMRLjdGo162qflzA8trQS4ziqymU4zqCvahpU7QlzHXF0Pct0xBNphvf6p6l3y54Mf6YQBomqUHthcYCEA== -"@sentry/[email protected]": - version "7.0.0-beta.2" - resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-7.0.0-beta.2.tgz#6edb5f80873980618c5f9b8fd4f96b9c8236b0f9" - integrity sha512-2PO0bRYBoWr/PWs7kCFuLK+lZ0F0B6O45oen8HK+YeizCaat6dlcu3/QNpFjv+lWVh6gDUgQ9nmQuO4L5a2dJA== +"@sentry/[email protected]": + version "7.0.0-rc.0" + resolved "https://registry.yarnpkg.com/@sentry/utils/-/utils-7.0.0-rc.0.tgz#d16c998db7ad07dacd78c6a64109b3857edfeffd" + integrity sha512-ZMRPcoLeXEXlltv48wpkJzGYC0JUYqzvFMJqzRfXyfwUi2HyVjHRRR8LqFbVP40qZkwLHyC1aXyov1L6kG+n5g== dependencies: - "@sentry/types" "7.0.0-beta.2" + "@sentry/types" "7.0.0-rc.0" tslib "^1.9.3" "@sinclair/typebox@^0.23.3":
ec2a82e616225ff32158f8a47a57496bd4dcfe05
2021-12-11 01:29:34
edwardgou-sentry
fix(dashboards): Added tag loader to issue widgets query search (#30542)
false
Added tag loader to issue widgets query search (#30542)
fix
diff --git a/static/app/components/dashboards/issueWidgetQueriesForm.tsx b/static/app/components/dashboards/issueWidgetQueriesForm.tsx index fdfef9174777e5..9dac2870a87df5 100644 --- a/static/app/components/dashboards/issueWidgetQueriesForm.tsx +++ b/static/app/components/dashboards/issueWidgetQueriesForm.tsx @@ -2,9 +2,12 @@ import * as React from 'react'; import styled from '@emotion/styled'; import cloneDeep from 'lodash/cloneDeep'; +import {fetchTagValues} from 'sentry/actionCreators/tags'; +import {Client} from 'sentry/api'; import {t} from 'sentry/locale'; import space from 'sentry/styles/space'; import {GlobalSelection, Organization, TagCollection} from 'sentry/types'; +import {getUtcDateString} from 'sentry/utils/dates'; import {explodeField, generateFieldAsString} from 'sentry/utils/discover/fields'; import withIssueTags from 'sentry/utils/withIssueTags'; import {DisplayType, WidgetQuery, WidgetType} from 'sentry/views/dashboardsV2/types'; @@ -15,6 +18,7 @@ import Field from 'sentry/views/settings/components/forms/field'; import WidgetQueryFields from './widgetQueryFields'; type Props = { + api: Client; organization: Organization; selection: GlobalSelection; query: WidgetQuery; @@ -50,6 +54,19 @@ class IssueWidgetQueriesForm extends React.Component<Props, State> { }; }; + tagValueLoader = (key: string, search: string) => { + const {organization, selection, api} = this.props; + const orgId = organization.slug; + const projectIds = selection.projects.map(id => id.toString()); + const endpointParams = { + start: getUtcDateString(selection.datetime.start), + end: getUtcDateString(selection.datetime.end), + statsPeriod: selection.datetime.period, + }; + + return fetchTagValues(api, orgId, key, search, projectIds, endpointParams); + }; + render() { const {organization, error, query, tags, fieldOptions, onChange} = this.props; const explodedFields = query.fields.map(field => explodeField({field})); @@ -91,8 +108,7 @@ class IssueWidgetQueriesForm extends React.Component<Props, State> { }} excludeEnvironment supportedTags={tags} - tagValueLoader={() => new Promise(() => [])} - savedSearch={undefined} + tagValueLoader={this.tagValueLoader} onSidebarToggle={() => undefined} /> </SearchConditionsWrapper> diff --git a/static/app/components/modals/addDashboardIssueWidgetModal.tsx b/static/app/components/modals/addDashboardIssueWidgetModal.tsx index 5e903a8fcca0fa..9f529361e9c66d 100644 --- a/static/app/components/modals/addDashboardIssueWidgetModal.tsx +++ b/static/app/components/modals/addDashboardIssueWidgetModal.tsx @@ -233,6 +233,7 @@ class AddDashboardIssueWidgetModal extends React.Component<Props, State> { /> </StyledField> <IssueWidgetQueriesForm + api={api} organization={organization} selection={querySelection} fieldOptions={fieldOptions} diff --git a/tests/js/spec/components/dashboards/issueWidgetQueriesForm.spec.tsx b/tests/js/spec/components/dashboards/issueWidgetQueriesForm.spec.tsx index a69fae7509aa12..dce177fa48827d 100644 --- a/tests/js/spec/components/dashboards/issueWidgetQueriesForm.spec.tsx +++ b/tests/js/spec/components/dashboards/issueWidgetQueriesForm.spec.tsx @@ -1,3 +1,4 @@ +import {initializeOrg} from 'sentry-test/initializeOrg'; import {mountWithTheme, screen, userEvent} from 'sentry-test/reactTestingLibrary'; import IssueWidgetQueriesForm from 'sentry/components/dashboards/issueWidgetQueriesForm'; @@ -5,8 +6,12 @@ import {FieldValueKind} from 'sentry/views/eventsV2/table/types'; import {generateFieldOptions} from 'sentry/views/eventsV2/utils'; describe('IssueWidgetQueriesForm', function () { - const organization = TestStubs.Organization(); + const {organization, routerContext} = initializeOrg({ + router: {orgId: 'orgId'}, + } as Parameters<typeof initializeOrg>[0]); + const api = new MockApiClient(); let onChangeHandler; + let tagsMock; beforeEach(() => { onChangeHandler = jest.fn(); @@ -31,6 +36,29 @@ describe('IssueWidgetQueriesForm', function () { method: 'POST', }); + tagsMock = MockApiClient.addMockResponse({ + url: '/organizations/org-slug/tags/event.type/values/', + method: 'GET', + body: [ + { + key: 'event.type', + name: 'default', + value: 'default', + count: 128467, + lastSeen: '2021-12-10T16:37:00Z', + firstSeen: '2021-12-09T16:37:02Z', + }, + { + key: 'event.type', + name: 'error', + value: 'error', + count: 50257, + lastSeen: '2021-12-10T16:36:51Z', + firstSeen: '2021-12-09T16:37:07Z', + }, + ], + }); + const fieldOptions = { 'field:issue': { label: 'issue', @@ -56,6 +84,7 @@ describe('IssueWidgetQueriesForm', function () { mountWithTheme( <IssueWidgetQueriesForm + api={api} organization={organization} selection={{ projects: [1], @@ -75,10 +104,19 @@ describe('IssueWidgetQueriesForm', function () { }} onChange={onChangeHandler} fieldOptions={fieldOptions as ReturnType<typeof generateFieldOptions>} - /> + />, + {context: routerContext} ); }); + it('fetches tag values when when focused on a lhs tag condition', async function () { + userEvent.type(screen.getAllByText('assigned:')[1], 'event.type:'); + await tick(); + expect(tagsMock).toHaveBeenCalled(); + expect(screen.getByText('default')).toBeInTheDocument(); + expect(screen.getByText('error')).toBeInTheDocument(); + }); + it('only calls onChange once when selecting a value from the autocomplete dropdown', async function () { userEvent.click(screen.getAllByText('assigned:')[1]); await tick();
f08694fcbe240c39ab21929ede31e399710f48bd
2024-01-31 21:28:47
Daniel Szoke
ref: Remove `start_transaction` from `OrganizationIntegrationSetupView` (#64272)
false
Remove `start_transaction` from `OrganizationIntegrationSetupView` (#64272)
ref
diff --git a/src/sentry/web/frontend/organization_integration_setup.py b/src/sentry/web/frontend/organization_integration_setup.py index 2fe111979db6d6..83f6465c44321f 100644 --- a/src/sentry/web/frontend/organization_integration_setup.py +++ b/src/sentry/web/frontend/organization_integration_setup.py @@ -4,6 +4,7 @@ from django.http import Http404 from django.http.response import HttpResponseBase from rest_framework.request import Request +from sentry_sdk.tracing import TRANSACTION_SOURCE_VIEW from sentry import features from sentry.features.exceptions import FeatureNotRegistered @@ -20,46 +21,33 @@ class OrganizationIntegrationSetupView(ControlSiloOrganizationView): csrf_protect = False def handle(self, request: Request, organization, provider_id) -> HttpResponseBase: - try: - with sentry_sdk.configure_scope() as scope: - parent_span_id = scope.span.span_id - trace_id = scope.span.trace_id - except AttributeError: - parent_span_id = None - trace_id = None + with sentry_sdk.configure_scope() as scope: + scope.set_transaction_name(f"integration.{provider_id}", source=TRANSACTION_SOURCE_VIEW) + + pipeline = IntegrationPipeline( + request=request, organization=organization, provider_key=provider_id + ) + + is_feature_enabled = {} + for feature in pipeline.provider.features: + feature_flag_name = "organizations:integrations-%s" % feature.value + try: + features.get(feature_flag_name, None) + is_feature_enabled[feature_flag_name] = features.has( + feature_flag_name, organization + ) + except FeatureNotRegistered: + is_feature_enabled[feature_flag_name] = True - with sentry_sdk.start_transaction( - op="integration.setup", - name=f"integration.{provider_id}", - parent_span_id=parent_span_id, - trace_id=trace_id, - sampled=True, - ): - pipeline = IntegrationPipeline( - request=request, organization=organization, provider_key=provider_id + if not any(is_feature_enabled.values()): + return pipeline.render_warning( + "At least one feature from this list has to be enabled in order to setup the integration:\n%s" + % "\n".join(is_feature_enabled) ) - is_feature_enabled = {} - for feature in pipeline.provider.features: - feature_flag_name = "organizations:integrations-%s" % feature.value - try: - features.get(feature_flag_name, None) - is_feature_enabled[feature_flag_name] = features.has( - feature_flag_name, organization - ) - except FeatureNotRegistered: - is_feature_enabled[feature_flag_name] = True - - if not any(is_feature_enabled.values()): - return pipeline.render_warning( - "At least one feature from this list has to be enabled in order to setup the integration:\n%s" - % "\n".join(is_feature_enabled) - ) - - if not pipeline.provider.can_add: - raise Http404 + if not pipeline.provider.can_add: + raise Http404 - pipeline.initialize() + pipeline.initialize() - response = pipeline.current_step() - return response + return pipeline.current_step()
6949fe7405f3dd31f7c30d36b2c8c2a48fec6152
2024-01-23 23:31:26
Scott Cooper
fix(issues): Hide stacktrace link for minified code (#63646)
false
Hide stacktrace link for minified code (#63646)
fix
diff --git a/static/app/components/events/interfaces/frame/deprecatedLine.tsx b/static/app/components/events/interfaces/frame/deprecatedLine.tsx index da927141e0aa86..44bcd3cb8245ec 100644 --- a/static/app/components/events/interfaces/frame/deprecatedLine.tsx +++ b/static/app/components/events/interfaces/frame/deprecatedLine.tsx @@ -391,7 +391,7 @@ export class DeprecatedLine extends Component<Props, State> { {t('Suspect Frame')} </Tag> ) : null} - {showStacktraceLinkInFrame && ( + {showStacktraceLinkInFrame && !shouldShowSourceMapDebuggerButton && ( <ErrorBoundary> <StacktraceLink frame={data}
2498ed7e7ef2a982d30b078ea4097d45d5c950ce
2024-03-14 05:32:04
Vu Luong
ref(theme): Update accent colors (#66933)
false
Update accent colors (#66933)
ref
diff --git a/static/app/utils/theme.tsx b/static/app/utils/theme.tsx index e1aca72ba565e1..9d73812f0be70b 100644 --- a/static/app/utils/theme.tsx +++ b/static/app/utils/theme.tsx @@ -41,35 +41,35 @@ export const lightColors = { translucentGray200: 'rgba(58, 17, 95, 0.14)', translucentGray100: 'rgba(45, 0, 85, 0.06)', - purple400: '#584AC0', + purple400: '#6559C5', purple300: '#6C5FC7', purple200: 'rgba(108, 95, 199, 0.5)', - purple100: 'rgba(108, 95, 199, 0.08)', + purple100: 'rgba(108, 95, 199, 0.09)', blue400: '#2562D4', blue300: '#3C74DD', blue200: 'rgba(60, 116, 221, 0.5)', blue100: 'rgba(60, 116, 221, 0.09)', - green400: '#268D75', + green400: '#207964', green300: '#2BA185', green200: 'rgba(43, 161, 133, 0.55)', - green100: 'rgba(43, 161, 133, 0.13)', + green100: 'rgba(43, 161, 133, 0.11)', - yellow400: '#E5A500', - yellow300: '#F5B000', - yellow200: 'rgba(245, 176, 0, 0.55)', - yellow100: 'rgba(245, 176, 0, 0.08)', + yellow400: '#856C00', + yellow300: '#EBC000', + yellow200: 'rgba(235, 192, 0, 0.7)', + yellow100: 'rgba(235, 192, 0, 0.14)', - red400: '#DF3338', + red400: '#CF2126', red300: '#F55459', red200: 'rgba(245, 84, 89, 0.5)', - red100: 'rgba(245, 84, 89, 0.09)', + red100: 'rgba(245, 84, 89, 0.1)', - pink400: '#E50675', + pink400: '#D1056B', pink300: '#F14499', pink200: 'rgba(249, 26, 138, 0.5)', - pink100: 'rgba(249, 26, 138, 0.1)', + pink100: 'rgba(249, 26, 138, 0.09)', }; /** @@ -108,35 +108,35 @@ export const darkColors = { translucentGray200: 'rgba(218, 184, 245, 0.16)', translucentGray100: 'rgba(208, 168, 240, 0.07)', - purple400: '#A397F7', + purple400: '#ABA0F8', purple300: '#7669D3', purple200: 'rgba(118, 105, 211, 0.27)', - purple100: 'rgba(118, 105, 211, 0.12)', + purple100: 'rgba(118, 105, 211, 0.11)', - blue400: '#70A2FF', + blue400: '#80ACFF', blue300: '#3070E8', blue200: 'rgba(48, 112, 232, 0.25)', blue100: 'rgba(48, 112, 232, 0.12)', - green400: '#1AB792', + green400: '#1CC49D', green300: '#1D876E', green200: 'rgba(29, 135, 110, 0.3)', - green100: 'rgba(29, 135, 110, 0.14)', + green100: 'rgba(29, 135, 110, 0.12)', - yellow400: '#E5A500', - yellow300: '#B28000', - yellow200: 'rgba(178, 128, 0, 0.25)', - yellow100: 'rgba(178, 128, 0, 0.1)', + yellow400: '#C7B000', + yellow300: '#A89500', + yellow200: 'rgba(168, 149, 0, 0.25)', + yellow100: 'rgba(168, 149, 0, 0.09)', - red400: '#F87277', + red400: '#F98A8F', red300: '#E12D33', red200: 'rgba(225, 45, 51, 0.25)', - red100: 'rgba(225, 45, 51, 0.12)', + red100: 'rgba(225, 45, 51, 0.15)', - pink400: '#E674AD', + pink400: '#EB8FBC', pink300: '#CE3B85', pink200: 'rgba(206, 59, 133, 0.25)', - pink100: 'rgba(206, 59, 133, 0.1)', + pink100: 'rgba(206, 59, 133, 0.13)', }; const prismLight = {
2295534d747b94efd9703fc713c1cdd739ddf998
2018-12-14 06:04:52
ted kaemming
fix(tsdb): Don't execute queries for empty key set (#11027)
false
Don't execute queries for empty key set (#11027)
fix
diff --git a/src/sentry/tsdb/snuba.py b/src/sentry/tsdb/snuba.py index cc3938f76f41a5..c0750471a80535 100644 --- a/src/sentry/tsdb/snuba.py +++ b/src/sentry/tsdb/snuba.py @@ -77,9 +77,12 @@ def get_data(self, model, keys, start, end, rollup=None, environment_id=None, start = to_datetime(series[0]) end = to_datetime(series[-1] + rollup) - result = snuba.query(start, end, groupby, None, keys_map, - aggregations, rollup, referrer='tsdb', - is_grouprelease=(model == TSDBModel.frequent_releases_by_group)) + if keys: + result = snuba.query(start, end, groupby, None, keys_map, + aggregations, rollup, referrer='tsdb', + is_grouprelease=(model == TSDBModel.frequent_releases_by_group)) + else: + result = {} if group_on_time: keys_map['time'] = series @@ -209,7 +212,8 @@ def flatten_keys(self, items): The output is a 2-tuple of ([level_1_keys], [all_level_2_keys]) """ if isinstance(items, collections.Mapping): - return (items.keys(), list(set.union(*(set(v) for v in items.values())))) + return (items.keys(), list(set.union(*(set(v) + for v in items.values())) if items else [])) elif isinstance(items, (collections.Sequence, collections.Set)): return (items, None) else: diff --git a/tests/snuba/tsdb/test_tsdb_backend.py b/tests/snuba/tsdb/test_tsdb_backend.py index f8f9fcdc93f638..23dcfb8f9e45c5 100644 --- a/tests/snuba/tsdb/test_tsdb_backend.py +++ b/tests/snuba/tsdb/test_tsdb_backend.py @@ -179,6 +179,13 @@ def test_range_groups(self): ], } + assert self.db.get_range( + TSDBModel.group, + [], + dts[0], dts[-1], + rollup=3600 + ) == {} + def test_range_releases(self): dts = [self.now + timedelta(hours=i) for i in range(4)] assert self.db.get_range( @@ -320,6 +327,13 @@ def test_distinct_counts_series_users(self): ], } + assert self.db.get_distinct_counts_series( + TSDBModel.users_affected_by_group, + [], + dts[0], dts[-1], + rollup=3600, + ) == {} + def get_distinct_counts_totals_users(self): assert self.db.get_distinct_counts_totals( TSDBModel.users_affected_by_group, @@ -351,6 +365,14 @@ def get_distinct_counts_totals_users(self): self.proj1.id: 2, } + assert self.db.get_distinct_counts_totals( + TSDBModel.users_affected_by_group, + [], + self.now, + self.now + timedelta(hours=4), + rollup=3600 + ) == {} + def test_most_frequent(self): assert self.db.get_most_frequent( TSDBModel.frequent_issues_by_project, @@ -365,6 +387,14 @@ def test_most_frequent(self): ], } + assert self.db.get_most_frequent( + TSDBModel.frequent_issues_by_project, + [], + self.now, + self.now + timedelta(hours=4), + rollup=3600, + ) == {} + def test_frequency_series(self): dts = [self.now + timedelta(hours=i) for i in range(4)] assert self.db.get_frequency_series( @@ -410,6 +440,13 @@ def test_frequency_series(self): ], } + assert self.db.get_frequency_series( + TSDBModel.frequent_releases_by_group, + {}, + dts[0], dts[-1], + rollup=3600, + ) == {} + def test_result_shape(self): """ Tests that the results from the different TSDB methods have the
ff67765152e27186360843e7834f64b6b7a7f7dd
2022-09-15 23:37:01
Dan Fuller
fix(perf_issues): Fix issue creation stats (#38888)
false
Fix issue creation stats (#38888)
fix
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py index bfa996151d582f..c797a871cca241 100644 --- a/src/sentry/event_manager.py +++ b/src/sentry/event_manager.py @@ -2057,9 +2057,9 @@ def _save_aggregate_performance(jobs: Sequence[Performance_Job], projects): # GROUP DOES NOT EXIST with sentry_sdk.start_span( - op="event_manager.create_group_transaction" + op="event_manager.create_performance_group_transaction" ) as span, metrics.timer( - "event_manager.create_group_transaction" + "event_manager.create_performance_group_transaction" ) as metric_tags, transaction.atomic(): span.set_tag("create_group_transaction.outcome", "no_group") metric_tags["create_group_transaction.outcome"] = "no_group"
66888a3aea25517d2d8da217fa9c9e9ee10a192e
2022-02-17 21:36:55
Markus Unterwaditzer
fix(release_health): Split up featureflag (#31898)
false
Split up featureflag (#31898)
fix
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py index 823f13c6073ac2..2ede68626ce3c4 100644 --- a/src/sentry/conf/server.py +++ b/src/sentry/conf/server.py @@ -1008,8 +1008,11 @@ def create_partitioned_queues(name): "organizations:metrics-extraction": False, # Enable switch metrics button on Performance, allowing switch to unsampled transaction metrics "organizations:metrics-performance-ui": False, - # True if the metrics backend should be checked against the sessions backend + # True if release-health related queries should be run against both + # backends (sessions and metrics dataset) "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 diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py index bdbebebf7d5087..0f6dfe052dda1e 100644 --- a/src/sentry/features/__init__.py +++ b/src/sentry/features/__init__.py @@ -141,6 +141,7 @@ 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) default_manager.add("organizations:reprocessing-v2", OrganizationFeature) default_manager.add("organizations:required-email-verification", OrganizationFeature, True) # NOQA default_manager.add("organizations:rule-page", OrganizationFeature) diff --git a/src/sentry/release_health/duplex.py b/src/sentry/release_health/duplex.py index 4a7a62a7d630eb..9989a8b5bfc374 100644 --- a/src/sentry/release_health/duplex.py +++ b/src/sentry/release_health/duplex.py @@ -536,7 +536,9 @@ def _dispatch_call_inner( tags={"has_errors": str(bool(errors)), **tags}, sample_rate=1.0, ) - if errors: + if errors and features.has( + "organizations-release-health-check-metrics-report", organization + ): # We heavily rely on Sentry's message sanitization to properly deduplicate this capture_message(f"{fn_name} - Release health metrics mismatch: {errors[0]}") except Exception:
ca2fc76a1d919fbf686689c7a9eba36f3bd1b0d1
2019-05-21 02:33:59
Lauryn Brown
feat(search): Convert SearchBoolean to Snuba (#13133)
false
Convert SearchBoolean to Snuba (#13133)
feat
diff --git a/src/sentry/api/event_search.py b/src/sentry/api/event_search.py index 7c796f85c9ab7f..22040e67557854 100644 --- a/src/sentry/api/event_search.py +++ b/src/sentry/api/event_search.py @@ -149,13 +149,6 @@ class InvalidSearchQuery(Exception): pass -def has_boolean_search_terms(search_terms): - for term in search_terms: - if isinstance(term, SearchBoolean): - return True - return False - - class SearchBoolean(namedtuple('SearchBoolean', 'left_term operator right_term')): BOOLEAN_AND = "AND" BOOLEAN_OR = "OR" @@ -347,7 +340,7 @@ def visit_time_filter(self, node, children): try: search_value = parse_datetime_string(search_value) except InvalidQuery as exc: - raise InvalidSearchQuery(exc.message) + raise InvalidSearchQuery(six.text_type(exc)) return SearchFilter(search_key, operator, SearchValue(search_value)) else: search_value = operator + search_value if operator != '=' else search_value @@ -359,7 +352,7 @@ def visit_rel_time_filter(self, node, children): try: from_val, to_val = parse_datetime_range(value.text) except InvalidQuery as exc: - raise InvalidSearchQuery(exc.message) + raise InvalidSearchQuery(six.text_type(exc)) # TODO: Handle negations if from_val is not None: @@ -383,7 +376,7 @@ def visit_specific_time_filter(self, node, children): try: from_val, to_val = parse_datetime_value(date_value) except InvalidQuery as exc: - raise InvalidSearchQuery(exc.message) + raise InvalidSearchQuery(six.text_type(exc)) # TODO: Handle negations here. This is tricky because these will be # separate filters, and to negate this range we need (< val or >= val). @@ -489,6 +482,27 @@ def parse_search_query(query): return SearchVisitor().visit(tree) +def convert_search_boolean_to_snuba_query(search_boolean): + def convert_term(term): + if isinstance(term, SearchFilter): + return convert_search_filter_to_snuba_query(term) + elif isinstance(term, SearchBoolean): + return convert_search_boolean_to_snuba_query(term) + else: + raise InvalidSearchQuery( + 'Attempted to convert term of unrecognized type %s into a snuba expression' % + term.__class__.__name__) + + if not search_boolean: + return search_boolean + + left = convert_term(search_boolean.left_term) + right = convert_term(search_boolean.right_term) + operator = search_boolean.operator.lower() + + return [operator, [left, right]] + + def convert_endpoint_params(params): return [ SearchFilter( @@ -579,10 +593,10 @@ def convert_search_filter_to_snuba_query(search_filter): def get_snuba_query_args(query=None, params=None): # NOTE: this function assumes project permissions check already happened - parsed_filters = [] + parsed_terms = [] if query is not None: try: - parsed_filters = parse_search_query(query) + parsed_terms = parse_search_query(query) except ParseError as e: raise InvalidSearchQuery( u'Parse error: %r (column %d)' % (e.expr.name, e.column()) @@ -595,29 +609,26 @@ def get_snuba_query_args(query=None, params=None): # Keys included as url params take precedent if same key is included in search if params is not None: - parsed_filters.extend(convert_endpoint_params(params)) + parsed_terms.extend(convert_endpoint_params(params)) kwargs = { 'conditions': [], 'filter_keys': {}, } - # TODO(lb): remove when boolean terms fully functional - if has_boolean_search_terms(parsed_filters): - kwargs['has_boolean_terms'] = True - - for _filter in parsed_filters: - # TODO(lb): remove when boolean terms fully functional - if isinstance(_filter, SearchBoolean): - continue + for term in parsed_terms: + if isinstance(term, SearchFilter): + snuba_name = term.key.snuba_name - snuba_name = _filter.key.snuba_name - - if snuba_name in ('start', 'end'): - kwargs[snuba_name] = _filter.value.value - elif snuba_name in ('project_id', 'issue'): - kwargs['filter_keys'][snuba_name] = _filter.value.value - else: - converted_filter = convert_search_filter_to_snuba_query(_filter) - kwargs['conditions'].append(converted_filter) + if snuba_name in ('start', 'end'): + kwargs[snuba_name] = term.value.value + elif snuba_name in ('project_id', 'issue'): + kwargs['filter_keys'][snuba_name] = term.value.value + else: + converted_filter = convert_search_filter_to_snuba_query(term) + kwargs['conditions'].append(converted_filter) + else: # SearchBoolean + # TODO(lb): remove when boolean terms fully functional + kwargs['has_boolean_terms'] = True + kwargs['conditions'].append(convert_search_boolean_to_snuba_query(term)) return kwargs diff --git a/tests/sentry/api/test_event_search.py b/tests/sentry/api/test_event_search.py index 3cedc505b5d6f3..c8ba12bcf31571 100644 --- a/tests/sentry/api/test_event_search.py +++ b/tests/sentry/api/test_event_search.py @@ -1066,6 +1066,64 @@ def test_malformed_groups(self): with pytest.raises(InvalidSearchQuery): get_snuba_query_args('(user.email:[email protected] OR user.email:[email protected]') + def test_boolean_term_simple(self): + assert get_snuba_query_args('user.email:[email protected] AND user.email:[email protected]') == { + 'conditions': [ + ['and', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]] + ], + 'filter_keys': {}, + 'has_boolean_terms': True, + } + assert get_snuba_query_args('user.email:[email protected] OR user.email:[email protected]') == { + 'conditions': [ + ['or', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]] + ], + 'filter_keys': {}, + 'has_boolean_terms': True, + } + assert get_snuba_query_args( + 'user.email:[email protected] AND user.email:[email protected] OR user.email:[email protected] AND user.email:[email protected] AND user.email:[email protected] OR user.email:[email protected] AND user.email:[email protected] OR user.email:[email protected] AND user.email:[email protected] AND user.email:[email protected]' + ) == { + 'conditions': [ + ['or', [ + ['and', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]], + ['or', [ + ['and', [ + ['email', '=', '[email protected]'], + ['and', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]] + ]], + ['or', [ + ['and', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]], + ['and', [ + ['email', '=', '[email protected]'], + ['and', [ + ['email', '=', '[email protected]'], + ['email', '=', '[email protected]'] + ]] + ]] + ]] + ]] + ]] + ], + 'filter_keys': {}, + 'has_boolean_terms': True, + } + class ConvertEndpointParamsTests(TestCase): def test_simple(self):
4cdc8df79fe66390d3923f7f3e110693ff185a3e
2020-08-01 01:27:11
Markus Unterwaditzer
fix: Prevent celery from printing out vegetables to the terminal (#20106)
false
Prevent celery from printing out vegetables to the terminal (#20106)
fix
diff --git a/src/sentry/monkey/__init__.py b/src/sentry/monkey/__init__.py index 6d094d2f6bb061..09f4208c58f10a 100644 --- a/src/sentry/monkey/__init__.py +++ b/src/sentry/monkey/__init__.py @@ -84,5 +84,21 @@ def patch_django_views_debug(): debug.get_safe_settings = lambda: {} -for patch in (patch_parse_cookie, patch_httprequest_repr, patch_django_views_debug): +def patch_celery_imgcat(): + # Remove Celery's attempt to display an rgb image in iTerm 2, as that + # attempt just prints out base64 trash in tmux. + try: + from celery.utils import term + except ImportError: + return + + term.imgcat = lambda *a, **kw: b"" + + +for patch in ( + patch_parse_cookie, + patch_httprequest_repr, + patch_django_views_debug, + patch_celery_imgcat, +): patch()
600dd9750a039344132ed601db9cbd50b4cd2c65
2024-01-23 23:54:54
Scott Cooper
fix(issues): Add internal integration default icon size (#63687)
false
Add internal integration default icon size (#63687)
fix
diff --git a/static/app/components/sentryAppComponentIcon.tsx b/static/app/components/sentryAppComponentIcon.tsx index 4775999609bf31..d9ce541310f50b 100644 --- a/static/app/components/sentryAppComponentIcon.tsx +++ b/static/app/components/sentryAppComponentIcon.tsx @@ -13,7 +13,7 @@ type Props = { * Icon Renderer for SentryAppComponents with UI * (e.g. Issue Linking, Stacktrace Linking) */ -function SentryAppComponentIcon({sentryAppComponent, size}: Props) { +function SentryAppComponentIcon({sentryAppComponent, size = 20}: Props) { const selectedAvatar = sentryAppComponent.sentryApp?.avatars?.find( ({color}) => color === false );
ba93aae37704b4a9c50075f41c7c234242ff61a2
2023-01-13 21:13:20
Evan Purkhiser
feat(ui): Fix alignment of shortID in IssueDetails header (#43223)
false
Fix alignment of shortID in IssueDetails header (#43223)
feat
diff --git a/static/app/views/organizationGroupDetails/header.tsx b/static/app/views/organizationGroupDetails/header.tsx index 0ee375b4aa816b..f664b0c57471f1 100644 --- a/static/app/views/organizationGroupDetails/header.tsx +++ b/static/app/views/organizationGroupDetails/header.tsx @@ -412,6 +412,7 @@ const ShortIdBreadrcumb = styled('div')` const StyledShortId = styled(ShortId)` font-family: ${p => p.theme.text.family}; font-size: ${p => p.theme.fontSizeMedium}; + line-height: 1; `; const HeaderRow = styled('div')`
c441a5d0fc4f87cd9ab1173652a95b2d201cf1cb
2024-08-08 01:48:20
Evan Purkhiser
feat(uptime): Add default name (#75761)
false
Add default name (#75761)
feat
diff --git a/src/sentry/uptime/endpoints/serializers.py b/src/sentry/uptime/endpoints/serializers.py index e2df2237665012..ea64297818586e 100644 --- a/src/sentry/uptime/endpoints/serializers.py +++ b/src/sentry/uptime/endpoints/serializers.py @@ -49,7 +49,7 @@ def serialize( return { "id": str(obj.id), "projectSlug": obj.project.slug, - "name": obj.name, + "name": obj.name or f"Uptime monitor of {obj.uptime_subscription.url}", "status": obj.uptime_status, "mode": obj.mode, "url": obj.uptime_subscription.url, diff --git a/tests/sentry/uptime/endpoints/test_serializers.py b/tests/sentry/uptime/endpoints/test_serializers.py index ce9d321d587e62..2eec763d144808 100644 --- a/tests/sentry/uptime/endpoints/test_serializers.py +++ b/tests/sentry/uptime/endpoints/test_serializers.py @@ -19,6 +19,25 @@ def test(self): "owner": None, } + def test_default_name(self): + """ + Right now no monitors have names. Once we name everything we can remove this + """ + uptime_monitor = self.create_project_uptime_subscription(name="") + result = serialize(uptime_monitor) + + assert result == { + "id": str(uptime_monitor.id), + "projectSlug": self.project.slug, + "name": f"Uptime monitor of {uptime_monitor.uptime_subscription.url}", + "status": uptime_monitor.uptime_status, + "mode": uptime_monitor.mode, + "url": uptime_monitor.uptime_subscription.url, + "intervalSeconds": uptime_monitor.uptime_subscription.interval_seconds, + "timeoutMs": uptime_monitor.uptime_subscription.timeout_ms, + "owner": None, + } + def test_owner(self): uptime_monitor = self.create_project_uptime_subscription(owner=self.user) result = serialize(uptime_monitor)
f0bce6e6a3dbdfa023da70fdba49dbc81d41883f
2018-03-06 05:07:43
Lyn Nagara
fix: Add back location.query (#7461)
false
Add back location.query (#7461)
fix
diff --git a/src/sentry/static/sentry/app/views/groupEvents.jsx b/src/sentry/static/sentry/app/views/groupEvents.jsx index 4bab2cdb0fbd3d..8244e4b5dfe89f 100644 --- a/src/sentry/static/sentry/app/views/groupEvents.jsx +++ b/src/sentry/static/sentry/app/views/groupEvents.jsx @@ -106,8 +106,7 @@ const GroupEvents = createReactClass({ loading: true, error: false, }); - - const query = {limit: 50, query: this.state.query}; + const query = {...this.props.location.query, limit: 50, query: this.state.query}; this.api.request(`/issues/${this.props.params.groupId}/events/`, { query,
6cc744add2a06453a3b6cd7a08152d90eca1507c
2024-02-27 13:00:12
Philipp Hofmann
ref(sdk-crash): SDK frame path field patterns (#65771)
false
SDK frame path field patterns (#65771)
ref
diff --git a/fixtures/sdk_crash_detection/crash_event_cocoa.py b/fixtures/sdk_crash_detection/crash_event_cocoa.py index ae39be30154d7d..85303393b43380 100644 --- a/fixtures/sdk_crash_detection/crash_event_cocoa.py +++ b/fixtures/sdk_crash_detection/crash_event_cocoa.py @@ -5,7 +5,7 @@ "function": "LoginViewController.viewDidAppear", "raw_function": "LoginViewController.viewDidAppear(Bool)", "symbol": "$s8Sentry9LoginViewControllerC13viewDidAppearyySbF", - "package": "SentryApp", + "package": "/private/var/containers/Bundle/Application/6D441916-FFB1-4346-9C51-3DD3E23046FC/Sentry.app/Sentry", "filename": "LoginViewController.swift", "abs_path": "/Users/sentry/git/iOS/Sentry/LoggedOut/LoginViewController.swift", "lineno": 196, diff --git a/src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py b/src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py index 48c19be054c007..2679ecae9d1591 100644 --- a/src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py +++ b/src/sentry/utils/sdk_crashes/sdk_crash_detection_config.py @@ -17,7 +17,7 @@ class SDKFrameConfig: function_patterns: set[str] - filename_patterns: set[str] + path_patterns: set[str] path_replacer: PathReplacer @@ -92,7 +92,7 @@ def build_sdk_crash_detection_configs() -> Sequence[SDKCrashDetectionConfig]: r"*(Sentry*)*", # Objective-C class extension categories r"SentryMX*", # MetricKit Swift classes }, - filename_patterns={"Sentry**"}, + path_patterns={"Sentry**"}, path_replacer=FixedPathReplacer(path="Sentry.framework"), ), # [SentrySDK crash] is a testing function causing a crash. @@ -122,7 +122,7 @@ def build_sdk_crash_detection_configs() -> Sequence[SDKCrashDetectionConfig]: }, sdk_frame_config=SDKFrameConfig( function_patterns=set(), - filename_patterns={ + path_patterns={ # Development path r"**/sentry-react-native/dist/**", # Production paths taken from https://github.com/getsentry/sentry-react-native/blob/037d5fa2f38b02eaf4ca92fda569e0acfd6c3ebe/package.json#L68-L77 diff --git a/src/sentry/utils/sdk_crashes/sdk_crash_detector.py b/src/sentry/utils/sdk_crashes/sdk_crash_detector.py index 0cd4d2af9f4ea4..5fa92187ea1d99 100644 --- a/src/sentry/utils/sdk_crashes/sdk_crash_detector.py +++ b/src/sentry/utils/sdk_crashes/sdk_crash_detector.py @@ -102,17 +102,14 @@ def is_sdk_frame(self, frame: Mapping[str, Any]) -> bool: if glob_match(function, patterns, ignorecase=True): return True - filename = frame.get("filename") - if filename: - for patterns in self.config.sdk_frame_config.filename_patterns: - if glob_match(filename, patterns, ignorecase=True): - return True - - return False + return self._path_patters_match_frame(self.config.sdk_frame_config.path_patterns, frame) def is_system_library_frame(self, frame: Mapping[str, Any]) -> bool: + return self._path_patters_match_frame(self.config.system_library_path_patterns, frame) + + def _path_patters_match_frame(self, path_patters: set[str], frame: Mapping[str, Any]) -> bool: for field in self.fields_containing_paths: - for pattern in self.config.system_library_path_patterns: + for pattern in path_patters: field_with_path = frame.get(field) if field_with_path and glob_match(field_with_path, pattern, ignorecase=True): return True diff --git a/tests/sentry/utils/sdk_crashes/conftest.py b/tests/sentry/utils/sdk_crashes/conftest.py index 7b7091e149bf88..64633cdb20be2a 100644 --- a/tests/sentry/utils/sdk_crashes/conftest.py +++ b/tests/sentry/utils/sdk_crashes/conftest.py @@ -1,5 +1,12 @@ import pytest +from sentry.utils.sdk_crashes.path_replacer import FixedPathReplacer +from sentry.utils.sdk_crashes.sdk_crash_detection_config import ( + SDKCrashDetectionConfig, + SDKFrameConfig, + SdkName, +) + @pytest.fixture def store_event(default_project, factories): @@ -7,3 +14,22 @@ def inner(data): return factories.store_event(data=data, project_id=default_project.id) return inner + + [email protected] +def empty_cocoa_config() -> SDKCrashDetectionConfig: + return SDKCrashDetectionConfig( + sdk_name=SdkName.Cocoa, + project_id=0, + sample_rate=0.0, + organization_allowlist=[], + sdk_names=[], + min_sdk_version="", + system_library_path_patterns=set(), + sdk_frame_config=SDKFrameConfig( + function_patterns=set(), + path_patterns=set(), + path_replacer=FixedPathReplacer(path=""), + ), + sdk_crash_ignore_functions_matchers=set(), + ) diff --git a/tests/sentry/utils/sdk_crashes/test_sdk_crash_detector.py b/tests/sentry/utils/sdk_crashes/test_sdk_crash_detector.py new file mode 100644 index 00000000000000..1d6c582a52255f --- /dev/null +++ b/tests/sentry/utils/sdk_crashes/test_sdk_crash_detector.py @@ -0,0 +1,17 @@ +import pytest + +from sentry.utils.sdk_crashes.sdk_crash_detector import SDKCrashDetector + + [email protected]("field_containing_path", ["package", "module", "abs_path", "filename"]) +def test_build_sdk_crash_detection_configs(empty_cocoa_config, field_containing_path): + + empty_cocoa_config.sdk_frame_config.path_patterns = {"Sentry**"} + + detector = SDKCrashDetector(empty_cocoa_config) + + frame = { + field_containing_path: "Sentry", + } + + assert detector.is_sdk_frame(frame) is True
e4c6ad69c22692e2999baa26d8bf8f44947cd1c1
2022-07-23 00:20:09
Varun Venkatesh
fix(slack): Fix broken url formatting (#36976)
false
Fix broken url formatting (#36976)
fix
diff --git a/src/sentry/notifications/notifications/activity/new_processing_issues.py b/src/sentry/notifications/notifications/activity/new_processing_issues.py index 4dd9b6e406e856..05dc560b5ab1e2 100644 --- a/src/sentry/notifications/notifications/activity/new_processing_issues.py +++ b/src/sentry/notifications/notifications/activity/new_processing_issues.py @@ -58,7 +58,7 @@ def get_notification_title(self, context: Mapping[str, Any] | None = None) -> st project_url = absolute_uri( f"/settings/{self.organization.slug}/projects/{self.project.slug}/processing-issues/" ) - return f"Processing issues on <{self.project.slug}|{project_url}" + return f"Processing issues on <{project_url}|{self.project.slug}>" def build_attachment_title(self, recipient: Team | User) -> str: return self.get_subject() diff --git a/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py b/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py index 4ed342f53f4cf6..3aeac8d4bf27f4 100644 --- a/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py +++ b/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py @@ -35,7 +35,7 @@ def test_new_processing_issue(self, mock_func): attachment, text = get_attachment() assert ( text - == f"Processing issues on <{self.project.slug}|http://testserver/settings/{self.organization.slug}/projects/{self.project.slug}/processing-issues/" + == f"Processing issues on <http://testserver/settings/{self.organization.slug}/projects/{self.project.slug}/processing-issues/|{self.project.slug}>" ) assert ( attachment["text"]
22049606aee476b43acee6d43108de29ee5d51a1
2023-12-20 18:48:27
ArthurKnaus
ref(onboarding-docs): Migrate python docs to new structure (#62078)
false
Migrate python docs to new structure (#62078)
ref
diff --git a/static/app/gettingStartedDocs/python/awslambda.spec.tsx b/static/app/gettingStartedDocs/python/awslambda.spec.tsx index d924275a5866bd..9c1311e75e06b6 100644 --- a/static/app/gettingStartedDocs/python/awslambda.spec.tsx +++ b/static/app/gettingStartedDocs/python/awslambda.spec.tsx @@ -1,18 +1,37 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './awslambda'; -import {GettingStartedWithAwsLambda, steps} from './awslambda'; - -describe('GettingStartedWithAwsLambda', function () { +describe('awslambda onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithAwsLambda dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Timeout Warning'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content', dsn: 'test-dsn'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/awslambda.tsx b/static/app/gettingStartedDocs/python/awslambda.tsx index a1c4c940d3e92e..fdf12c1c34f9a3 100644 --- a/static/app/gettingStartedDocs/python/awslambda.tsx +++ b/static/app/gettingStartedDocs/python/awslambda.tsx @@ -1,174 +1,143 @@ -import {Fragment} from 'react'; import styled from '@emotion/styled'; import Alert from 'sentry/components/alert'; import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; +type Params = DocsParams; + +const getSdkSetupSnippet = (params: Params) => ` +import sentry_sdk +from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% +sentry_sdk.init( + dsn="${params.dsn}", + integrations=[AwsLambdaIntegration()],${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; + profiles_sample_rate=1.0,` + : '' + } +) + +def my_function(event, context): + ....`; + +const getTimeoutWarningSnippet = (params: Params) => ` +sentry_sdk.init( + dsn="${params.dsn}", + integrations=[ + AwsLambdaIntegration(timeout_warning=True), + ], +)`; -const introduction = ( - <p> - {tct( +const onboarding: OnboardingConfig = { + introduction: () => + tct( 'Create a deployment package on your local machine and install the required dependencies in the deployment package. For more information, see [link:AWS Lambda deployment package in Python].', { link: ( <ExternalLink href="https://docs.aws.amazon.com/lambda/latest/dg/python-package.html" /> ), } - )} - </p> -); - -export const steps = ({ - dsn, - sentryInitContent, -}: { - dsn: string; - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p>{tct('Install our Python SDK using [code:pip]:', {code: <code />})}</p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install --upgrade sentry-sdk', - }, - ], - }, - { - type: StepType.CONFIGURE, - description: t( - 'You can use the AWS Lambda integration for the Python SDK like this:' ), - configurations: [ - { - language: 'python', - code: ` -import sentry_sdk -from sentry_sdk.integrations.aws_lambda import AwsLambdaIntegration - -sentry_sdk.init( -${sentryInitContent} -) - -def my_function(event, context): - .... - `, - }, - ], - additionalInfo: ( - <p> - {tct("Check out Sentry's [link:AWS sample apps] for detailed examples.", { + install: () => [ + { + type: StepType.INSTALL, + description: tct('Install our Python SDK using [code:pip]:', {code: <code />}), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: t( + 'You can use the AWS Lambda integration for the Python SDK like this:' + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + additionalInfo: tct( + "Check out Sentry's [link:AWS sample apps] for detailed examples.", + { link: ( <ExternalLink href="https://github.com/getsentry/examples/tree/master/aws-lambda/python" /> ), - })} - </p> - ), - }, - { - title: t('Timeout Warning'), - description: ( - <p> - {tct( - 'The timeout warning reports an issue when the function execution time is near the [link:configured timeout].', - { - link: ( - <ExternalLink href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-common.html" /> - ), - } - )} - </p> - ), - configurations: [ - { - description: ( - <p> - {tct( - 'To enable the warning, update the SDK initialization to set [codeTimeout:timeout_warning] to [codeStatus:true]:', - {codeTimeout: <code />, codeStatus: <code />} - )} - </p> - ), - language: 'python', - code: ` -sentry_sdk.init( - dsn="${dsn}", - integrations=[ - AwsLambdaIntegration(timeout_warning=True), + } + ), + }, + { + title: t('Timeout Warning'), + description: tct( + 'The timeout warning reports an issue when the function execution time is near the [link:configured timeout].', + { + link: ( + <ExternalLink href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-function-common.html" /> + ), + } + ), + configurations: [ + { + description: tct( + 'To enable the warning, update the SDK initialization to set [codeTimeout:timeout_warning] to [codeStatus:true]:', + {codeTimeout: <code />, codeStatus: <code />} + ), + language: 'python', + code: getTimeoutWarningSnippet(params), + }, + { + description: t( + 'The timeout warning is sent only if the timeout in the Lambda Function configuration is set to a value greater than one second.' + ), + }, + ], + additionalInfo: ( + <AlertWithMarginBottom type="info"> + {tct( + 'If you are using another web framework inside of AWS Lambda, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.', + { + link: ( + <ExternalLink href="https://docs.sentry.io/platforms/python/#integrations" /> + ), + } + )} + </AlertWithMarginBottom> + ), + }, ], -) - `, - }, - ], - additionalInfo: t( - 'The timeout warning is sent only if the timeout in the Lambda Function configuration is set to a value greater than one second.' - ), - }, -]; -// Configuration End - -export function GettingStartedWithAwsLambda({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [ - ` dsn="${dsn}",`, - ` integrations=[AwsLambdaIntegration()],`, - ]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); + verify: () => [], +}; - return ( - <Fragment> - <Layout - introduction={introduction} - steps={steps({dsn, sentryInitContent: sentryInitContent.join('\n')})} - {...props} - /> - <AlertWithMarginBottom type="info"> - {tct( - 'If you are using another web framework inside of AWS Lambda, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.', - { - link: ( - <ExternalLink href="https://docs.sentry.io/platforms/python/#integrations" /> - ), - } - )} - </AlertWithMarginBottom> - </Fragment> - ); -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithAwsLambda; +export default docs; const AlertWithMarginBottom = styled(Alert)` margin-top: ${space(2)}; diff --git a/static/app/gettingStartedDocs/python/celery.spec.tsx b/static/app/gettingStartedDocs/python/celery.spec.tsx index 77b2934d99d586..130b2a5370129c 100644 --- a/static/app/gettingStartedDocs/python/celery.spec.tsx +++ b/static/app/gettingStartedDocs/python/celery.spec.tsx @@ -1,18 +1,39 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './celery'; -import {GettingStartedWithCelery, steps} from './celery'; - -describe('GettingStartedWithCelery', function () { +describe('celery onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithCelery dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Standalone Setup'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Setup With Django'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/celery.tsx b/static/app/gettingStartedDocs/python/celery.tsx index 595fe3e3b1d2c6..c293f501f0fb0c 100644 --- a/static/app/gettingStartedDocs/python/celery.tsx +++ b/static/app/gettingStartedDocs/python/celery.tsx @@ -4,204 +4,184 @@ import styled from '@emotion/styled'; import Alert from 'sentry/components/alert'; import {CodeSnippet} from 'sentry/components/codeSnippet'; import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; +type Params = DocsParams; + +const getSdkSetupSnippet = (params: Params) => ` +import sentry_sdk -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% +sentry_sdk.init( + dsn="${params.dsn}",${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% # of sampled transactions. # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; - -const introduction = ( - <p> - {tct('The celery integration adds support for the [link:Celery Task Queue System].', { + profiles_sample_rate=1.0,` + : '' + } +)`; + +const onboarding: OnboardingConfig = { + introduction: () => + tct('The celery integration adds support for the [link:Celery Task Queue System].', { link: <ExternalLink href="https://docs.celeryq.dev/en/stable/" />, - })} - </p> -); - -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p> - {tct('Install [code:sentry-sdk] from PyPI with the [code:celery] extra:', { + }), + install: () => [ + { + type: StepType.INSTALL, + description: tct( + 'Install [code:sentry-sdk] from PyPI with the [code:celery] extra:', + { code: <code />, - })} - </p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install --upgrade sentry-sdk[celery]', - }, - ], - }, - { - type: StepType.CONFIGURE, - description: ( - <div> - <p> - {tct( - 'If you have the [code:celery] package in your dependencies, the Celery integration will be enabled automatically when you initialize the Sentry SDK.', - { - code: <code />, - } - )} - </p> - <p> - {tct( - 'Make sure that the call to [code:init] is loaded on worker startup, and not only in the module where your tasks are defined. Otherwise, the initialization happens too late and events might end up not being reported.', - { - code: <code />, - } - )} - </p> - </div> - ), - configurations: [ - { - language: 'python', - code: ` -import sentry_sdk - -sentry_sdk.init( -${sentryInitContent} -) - `, - }, - ], - additionalInfo: ( - <Fragment> - <h5>{t('Standalone Setup')}</h5> - {t("If you're using Celery standalone, there are two ways to set this up:")} - <ul> - <li> + } + ), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk[celery]', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: ( + <div> + <p> + {tct( + 'If you have the [code:celery] package in your dependencies, the Celery integration will be enabled automatically when you initialize the Sentry SDK.', + { + code: <code />, + } + )} + </p> + <p> {tct( - "Initializing the SDK in the configuration file loaded with Celery's [code:--config] parameter", + 'Make sure that the call to [code:init] is loaded on worker startup, and not only in the module where your tasks are defined. Otherwise, the initialization happens too late and events might end up not being reported.', { code: <code />, } )} - </li> - <li> + </p> + </div> + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + additionalInfo: ( + <Fragment> + <h5>{t('Standalone Setup')}</h5> + {t("If you're using Celery standalone, there are two ways to set this up:")} + <ul> + <li> + {tct( + "Initializing the SDK in the configuration file loaded with Celery's [code:--config] parameter", + { + code: <code />, + } + )} + </li> + <li> + {tct( + 'Initializing the SDK by hooking it to either the [celerydInit: celeryd_init] or [workerInit: worker_init] signals:', + { + celerydInit: ( + <ExternalLink href="https://docs.celeryq.dev/en/stable/userguide/signals.html?#celeryd-init" /> + ), + workerInit: ( + <ExternalLink href="https://docs.celeryq.dev/en/stable/userguide/signals.html?#worker-init" /> + ), + } + )} + <CodeSnippet dark language="python"> + {`import sentry_sdk + from celery import Celery, signals + + app = Celery("myapp") + + #@signals.worker_init.connect + @signals.celeryd_init.connect + def init_sentry(**_kwargs): + sentry_sdk.init(...) # same as above + `} + </CodeSnippet> + </li> + </ul> + <h5>{t('Setup With Django')}</h5> + <p> {tct( - 'Initializing the SDK by hooking it to either the [celerydInit: celeryd_init] or [workerInit: worker_init] signals:', + "If you're using Celery with Django in a conventional setup, have already initialized the SDK in [settingsLink:your settings.py], and have Celery using the same settings with [celeryDocsLinks:config_from_object], you don't need to initialize the SDK separately for Celery.", { - celerydInit: ( - <ExternalLink href="https://docs.celeryq.dev/en/stable/userguide/signals.html?#celeryd-init" /> + settingsLink: ( + <ExternalLink href="https://docs.sentry.io/platforms/python/guides/django/#configure" /> ), - workerInit: ( - <ExternalLink href="https://docs.celeryq.dev/en/stable/userguide/signals.html?#worker-init" /> + celeryDocsLinks: ( + <ExternalLink href="https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html" /> ), } )} - <CodeSnippet dark language="python"> - {`import sentry_sdk -from celery import Celery, signals - -app = Celery("myapp") - -#@signals.worker_init.connect [email protected]_init.connect -def init_sentry(**_kwargs): - sentry_sdk.init(...) # same as above - `} - </CodeSnippet> - </li> - </ul> - <h5>{t('Setup With Django')}</h5> - <p> - {tct( - "If you're using Celery with Django in a conventional setup, have already initialized the SDK in [settingsLink:your settings.py], and have Celery using the same settings with [celeryDocsLinks:config_from_object], you don't need to initialize the SDK separately for Celery.", - { - settingsLink: ( - <ExternalLink href="https://docs.sentry.io/platforms/python/guides/django/#configure" /> - ), - celeryDocsLinks: ( - <ExternalLink href="https://docs.celeryq.dev/en/stable/django/first-steps-with-django.html" /> - ), - } - )} - </p> - </Fragment> - ), - }, - { - type: StepType.VERIFY, - description: ( - <div> - <p> - {t( - "To verify if your SDK is initialized on worker start, you can pass `debug=True` to `sentry_sdk.init()` to see extra output when the SDK is initialized. If the output appears during worker startup and not only after a task has started, then it's working properly." - )} - </p> - <AlertWithMarginBottom type="info"> - {tct( - `Sentry uses custom message headers for distributed tracing. For Celery versions 4.x, with [celeryDocLink: message protocol of version 1], this functionality is broken, and Celery fails to propagate custom headers to the worker. Protocol version 2, which is the default since Celery version 4.0, is not affected. - - The fix for the custom headers propagation issue was introduced to Celery project ([celeryPRLink: PR]) starting with version 5.0.1. However, the fix was not backported to versions 4.x. - `, - { - celeryDocLink: ( - <ExternalLink href="https://docs.celeryq.dev/en/stable/internals/protocol.html#version-1" /> - ), - celeryPRLink: ( - <ExternalLink href="https://github.com/celery/celery/pull/6374" /> - ), - } - )} - </AlertWithMarginBottom> - </div> - ), - }, -]; -// Configuration End - -export function GettingStartedWithCelery({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [` dsn="${dsn}",`]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); - - return ( - <Layout - introduction={introduction} - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} + </p> + </Fragment> + ), + }, + ], + verify: () => [ + { + type: StepType.VERIFY, + description: ( + <Fragment> + <p> + {t( + "To verify if your SDK is initialized on worker start, you can pass `debug=True` to `sentry_sdk.init()` to see extra output when the SDK is initialized. If the output appears during worker startup and not only after a task has started, then it's working properly." + )} + </p> + <AlertWithMarginBottom type="info"> + {tct( + `Sentry uses custom message headers for distributed tracing. For Celery versions 4.x, with [celeryDocLink: message protocol of version 1], this functionality is broken, and Celery fails to propagate custom headers to the worker. Protocol version 2, which is the default since Celery version 4.0, is not affected. -export default GettingStartedWithCelery; + The fix for the custom headers propagation issue was introduced to Celery project ([celeryPRLink: PR]) starting with version 5.0.1. However, the fix was not backported to versions 4.x. + `, + { + celeryDocLink: ( + <ExternalLink href="https://docs.celeryq.dev/en/stable/internals/protocol.html#version-1" /> + ), + celeryPRLink: ( + <ExternalLink href="https://github.com/celery/celery/pull/6374" /> + ), + } + )} + </AlertWithMarginBottom> + </Fragment> + ), + }, + ], +}; + +const docs: Docs = { + onboarding, +}; + +export default docs; const AlertWithMarginBottom = styled(Alert)` margin-top: ${space(2)}; diff --git a/static/app/gettingStartedDocs/python/chalice.spec.tsx b/static/app/gettingStartedDocs/python/chalice.spec.tsx index 2cc9386f4ae36a..48b8589e8be745 100644 --- a/static/app/gettingStartedDocs/python/chalice.spec.tsx +++ b/static/app/gettingStartedDocs/python/chalice.spec.tsx @@ -1,18 +1,39 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './chalice'; -import {GettingStartedWithChalice, steps} from './chalice'; - -describe('GettingStartedWithChalice', function () { +describe('chalice onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithChalice dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText( + textWithMarkupMatcher(/pip install --upgrade sentry-sdk\[chalice\]/) + ) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/chalice.tsx b/static/app/gettingStartedDocs/python/chalice.tsx index cd2b6116190103..2a0fb93cddc0ac 100644 --- a/static/app/gettingStartedDocs/python/chalice.tsx +++ b/static/app/gettingStartedDocs/python/chalice.tsx @@ -1,74 +1,42 @@ -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p> - {tct( - 'Install [sentrySdkCode:sentry-sdk] from PyPI with the [sentryBotteCode:chalice] extra:', - { - sentrySdkCode: <code />, - sentryBotteCode: <code />, - } - )} - </p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install --upgrade sentry-sdk[chalice]', - }, - ], - }, - { - type: StepType.CONFIGURE, - description: t( - 'To configure the SDK, initialize it with the integration before or after your app has been initialized:' - ), - configurations: [ - { - language: 'python', - code: ` +type Params = DocsParams; + +const getSdkSetupSnippet = (params: Params) => ` import sentry_sdk from chalice import Chalice from sentry_sdk.integrations.chalice import ChaliceIntegration - sentry_sdk.init( -${sentryInitContent} + dsn="${params.dsn}", + integrations=[ChaliceIntegration()],${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } ) -app = Chalice(app_name="appname") - `, - }, - ], - }, - { - type: StepType.VERIFY, - description: ( - <p>{t('To verify that everything is working trigger an error on purpose:')}</p> - ), - configurations: [ - { - language: 'python', - code: `from chalice import Chalice - -sentry_sdk.init( -${sentryInitContent} -) - -app = Chalice(app_name="helloworld") +app = Chalice(app_name="appname")`; +const getVerifySnippet = () => ` @app.schedule(Rate(1, unit=Rate.MINUTES)) def every_minute(event): 1/0 # raises an error @@ -76,40 +44,63 @@ def every_minute(event): @app.route("/") def index(): 1/0 # raises an error - return {"hello": "world"}`, - }, - ], - additionalInfo: ( - <p> - {tct( - 'When you enter the [code:"/"] route or the scheduled task is run, an error event will be sent to Sentry.', - { - code: <code />, - } - )} - </p> - ), - }, -]; -// Configuration End - -export function GettingStartedWithChalice({dsn, ...props}: ModuleProps) { - const otherConfigs: string[] = []; + return {"hello": "world"}`; - let sentryInitContent: string[] = [ - ` dsn="${dsn}",`, - ` integrations=[ChaliceIntegration()],`, - ]; +const onboarding: OnboardingConfig = { + install: () => [ + { + type: StepType.INSTALL, + description: tct( + 'Install [sentrySdkCode:sentry-sdk] from PyPI with the [sentryBotteCode:chalice] extra:', + { + sentrySdkCode: <code />, + sentryBotteCode: <code />, + } + ), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk[chalice]', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: t( + 'To configure the SDK, initialize it with the integration before or after your app has been initialized:' + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + }, + ], + verify: () => [ + { + type: StepType.VERIFY, + description: t('To verify that everything is working trigger an error on purpose:'), + configurations: [ + { + language: 'python', + code: getVerifySnippet(), + }, + ], + additionalInfo: tct( + 'When you enter the [code:"/"] route or the scheduled task is run, an error event will be sent to Sentry.', + { + code: <code />, + } + ), + }, + ], +}; - sentryInitContent = sentryInitContent.concat(otherConfigs); +const docs: Docs = { + onboarding, +}; - return ( - <Layout - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} -export default GettingStartedWithChalice; +export default docs; diff --git a/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx b/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx index 1362edf2b559ec..a219ceb386348c 100644 --- a/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx +++ b/static/app/gettingStartedDocs/python/gcpfunctions.spec.tsx @@ -1,18 +1,37 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './gcpfunctions'; -import {GettingStartedWithGCPFunctions, steps} from './gcpfunctions'; - -describe('GettingStartedWithGCPFunctions', function () { +describe('gcpfunctions onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithGCPFunctions dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Timeout Warning'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content', dsn: 'test-dsn'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/gcpfunctions.tsx b/static/app/gettingStartedDocs/python/gcpfunctions.tsx index 9bbfc294b59428..b30abb7c7bf9e6 100644 --- a/static/app/gettingStartedDocs/python/gcpfunctions.tsx +++ b/static/app/gettingStartedDocs/python/gcpfunctions.tsx @@ -1,160 +1,136 @@ -import {Fragment} from 'react'; import styled from '@emotion/styled'; import Alert from 'sentry/components/alert'; import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; - -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% - # of sampled transactions. - # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; +type Params = DocsParams; -export const steps = ({ - dsn, - sentryInitContent, -}: { - dsn: string; - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p>{tct('Install our Python SDK using [code:pip]:', {code: <code />})}</p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install --upgrade sentry-sdk', - }, - ], - }, - { - type: StepType.CONFIGURE, - description: t( - 'You can use the Google Cloud Functions integration for the Python SDK like this:' - ), - configurations: [ - { - language: 'python', - code: ` +const getSdkSetupSnippet = (params: Params) => ` import sentry_sdk from sentry_sdk.integrations.gcp import GcpIntegration sentry_sdk.init( -${sentryInitContent} + dsn="${params.dsn}", + integrations=[GcpIntegration()],${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } ) def http_function_entrypoint(request): - ... - `, - }, - ], - additionalInfo: ( - <p> - {tct("Check out Sentry's [link:GCP sample apps] for detailed examples.", { - link: ( - <ExternalLink href="https://github.com/getsentry/examples/tree/master/gcp-cloud-functions" /> - ), - })} - </p> - ), - }, - { - title: t('Timeout Warning'), - description: ( - <p> - {tct( - 'The timeout warning reports an issue when the function execution time is near the [link:configured timeout].', - { - link: ( - <ExternalLink href="https://cloud.google.com/functions/docs/concepts/execution-environment#timeout" /> - ), - } - )} - </p> - ), - configurations: [ - { - description: ( - <p> - {tct( - 'To enable the warning, update the SDK initialization to set [codeTimeout:timeout_warning] to [codeStatus:true]:', - {codeTimeout: <code />, codeStatus: <code />} - )} - </p> - ), - language: 'python', - code: ` + ...`; + +const getTimeoutWarningSnippet = (params: Params) => ` sentry_sdk.init( - dsn="${dsn}", + dsn="${params.dsn}", integrations=[ GcpIntegration(timeout_warning=True), ], -) - `, - }, - ], - additionalInfo: t( - 'The timeout warning is sent only if the timeout in the Cloud Function configuration is set to a value greater than one second.' - ), - }, -]; -// Configuration End - -export function GettingStartedWithGCPFunctions({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [ - ` dsn="${dsn}",`, - ` integrations=[GcpIntegration()],`, - ]; +)`; - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); +const onboarding: OnboardingConfig = { + install: () => [ + { + type: StepType.INSTALL, + description: ( + <p>{tct('Install our Python SDK using [code:pip]:', {code: <code />})}</p> + ), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: t( + 'You can use the Google Cloud Functions integration for the Python SDK like this:' + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + additionalInfo: tct( + "Check out Sentry's [link:GCP sample apps] for detailed examples.", + { + link: ( + <ExternalLink href="https://github.com/getsentry/examples/tree/master/gcp-cloud-functions" /> + ), + } + ), + }, + { + title: t('Timeout Warning'), + description: tct( + 'The timeout warning reports an issue when the function execution time is near the [link:configured timeout].', + { + link: ( + <ExternalLink href="https://cloud.google.com/functions/docs/concepts/execution-environment#timeout" /> + ), + } + ), + configurations: [ + { + description: tct( + 'To enable the warning, update the SDK initialization to set [codeTimeout:timeout_warning] to [codeStatus:true]:', + {codeTimeout: <code />, codeStatus: <code />} + ), + language: 'python', + code: getTimeoutWarningSnippet(params), + }, + { + description: t( + 'The timeout warning is sent only if the timeout in the Cloud Function configuration is set to a value greater than one second.' + ), + }, + ], + additionalInfo: ( + <AlertWithMarginBottom type="info"> + {tct( + 'If you are using a web framework in your Cloud Function, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.', + { + link: ( + <ExternalLink href="https://docs.sentry.io/platforms/python/#integrations" /> + ), + } + )} + </AlertWithMarginBottom> + ), + }, + ], + verify: () => [], +}; - return ( - <Fragment> - <Layout - steps={steps({dsn, sentryInitContent: sentryInitContent.join('\n')})} - {...props} - /> - <AlertWithMarginBottom type="info"> - {tct( - 'If you are using a web framework in your Cloud Function, the framework might catch those exceptions before we get to see them. Make sure to enable the framework specific integration as well, if one exists. See [link:Integrations] for more information.', - { - link: ( - <ExternalLink href="https://docs.sentry.io/platforms/python/#integrations" /> - ), - } - )} - </AlertWithMarginBottom> - </Fragment> - ); -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithGCPFunctions; +export default docs; const AlertWithMarginBottom = styled(Alert)` margin-top: ${space(2)}; diff --git a/static/app/gettingStartedDocs/python/pylons.spec.tsx b/static/app/gettingStartedDocs/python/pylons.spec.tsx index ef035a07f4254d..121a1878669b2e 100644 --- a/static/app/gettingStartedDocs/python/pylons.spec.tsx +++ b/static/app/gettingStartedDocs/python/pylons.spec.tsx @@ -1,18 +1,21 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './pylons'; -import {GettingStartedWithPylons, steps} from './pylons'; - -describe('GettingStartedWithPylons', function () { +describe('pylons onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithPylons dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Logger setup'})).toBeInTheDocument(); - // Steps - for (const step of steps()) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install raven --upgrade/)) + ).toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/pylons.tsx b/static/app/gettingStartedDocs/python/pylons.tsx index a775da153d8ede..55443f357da2cc 100644 --- a/static/app/gettingStartedDocs/python/pylons.tsx +++ b/static/app/gettingStartedDocs/python/pylons.tsx @@ -1,72 +1,25 @@ -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -export const steps = ({ - dsn, -}: Partial<Pick<ModuleProps, 'dsn'>> = {}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p> - {tct( - 'If you haven’t already, start by downloading Raven. The easiest way is with [code:pip]:', - {code: <code />} - )} - </p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install raven --upgrade', - }, - ], - }, - { - title: t('WSGI Middleware'), - configurations: [ - { - language: 'python', - description: t( - 'A Pylons-specific middleware exists to enable easy configuration from settings:' - ), - code: ` +type Params = DocsParams; + +const getMidlewareSetupSnippet = () => ` from raven.contrib.pylons import Sentry -application = Sentry(application, config) - `, - }, - { - language: 'ini', - description: t('Configuration is handled via the sentry namespace:'), - code: ` +application = Sentry(application, config)`; + +const getConfigurationSnippet = (params: Params) => ` [sentry] -dsn=${dsn} +dsn=${params.dsn} include_paths=my.package,my.other.package, -exclude_paths=my.package.crud - `, - }, - ], - }, - { - title: t('Logger setup'), - configurations: [ - { - language: 'python', - description: ( - <p> - {tct( - 'Add the following lines to your project’s [initCode:.ini] file to setup [sentryHandlerCode:SentryHandler]:', - { - initCode: <code />, - sentryHandlerCode: <code />, - } - )} - </p> - ), - code: ` +exclude_paths=my.package.crud`; + +const getLoggerSnippet = () => ` [loggers] keys = root, sentry @@ -100,17 +53,65 @@ formatter = generic [formatter_generic] format = %(asctime)s,%(msecs)03d %(levelname)-5.5s [%(name)s] %(message)s -datefmt = %H:%M:%S - `, - }, - ], - additionalInfo: t('You may want to set up other loggers as well.'), - }, -]; -// Configuration End +datefmt = %H:%M:%S`; + +const onboarding: OnboardingConfig = { + install: () => [ + { + type: StepType.INSTALL, + description: tct( + 'If you haven’t already, start by downloading Raven. The easiest way is with [code:pip]:', + {code: <code />} + ), + configurations: [ + { + language: 'bash', + code: 'pip install raven --upgrade', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + configurations: [ + { + language: 'python', + description: t( + 'A Pylons-specific middleware exists to enable easy configuration from settings:' + ), + code: getMidlewareSetupSnippet(), + }, + { + language: 'ini', + description: t('Configuration is handled via the sentry namespace:'), + code: getConfigurationSnippet(params), + }, + ], + }, + { + title: t('Logger setup'), + configurations: [ + { + language: 'python', + description: tct( + 'Add the following lines to your project’s [initCode:.ini] file to setup [sentryHandlerCode:SentryHandler]:', + { + initCode: <code />, + sentryHandlerCode: <code />, + } + ), + code: getLoggerSnippet(), + }, + ], + additionalInfo: t('You may want to set up other loggers as well.'), + }, + ], + verify: () => [], +}; -export function GettingStartedWithPylons({dsn, ...props}: ModuleProps) { - return <Layout steps={steps({dsn})} {...props} />; -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithPylons; +export default docs; diff --git a/static/app/gettingStartedDocs/python/python.spec.tsx b/static/app/gettingStartedDocs/python/python.spec.tsx index a18a9bb558fb99..6fd473c2a8683f 100644 --- a/static/app/gettingStartedDocs/python/python.spec.tsx +++ b/static/app/gettingStartedDocs/python/python.spec.tsx @@ -1,18 +1,37 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './python'; -import {GettingStartedWithPython, steps} from './python'; - -describe('GettingStartedWithPython', function () { +describe('python onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithPython dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps()) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/python.tsx b/static/app/gettingStartedDocs/python/python.tsx index 115283814b1c3d..4e2612889b1695 100644 --- a/static/app/gettingStartedDocs/python/python.tsx +++ b/static/app/gettingStartedDocs/python/python.tsx @@ -1,110 +1,85 @@ -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; - -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% - # of sampled transactions. - # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; +type Params = DocsParams; -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent?: string; -} = {}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <p> - {tct('Install our Python SDK using [code:pip]:', { - code: <code />, - })} - </p> - ), - configurations: [ - { - language: 'bash', - code: 'pip install --upgrade sentry-sdk', - }, - ], - }, - { - type: StepType.CONFIGURE, - description: t( - "Import and initialize the Sentry SDK early in your application's setup:" - ), - configurations: [ - { - language: 'python', - code: ` +const getSdkSetupSnippet = (params: Params) => ` import sentry_sdk sentry_sdk.init( -${sentryInitContent} -) `, - }, - ], - additionalInfo: ( - <p> - {tct( - 'The above configuration captures both error and performance data. To reduce the volume of performance data captured, change [code:traces_sample_rate] to a value between 0 and 1.', - {code: <code />} - )} - </p> - ), - }, - { - type: StepType.VERIFY, - description: t( - 'One way to verify your setup is by intentionally causing an error that breaks your application.' - ), - configurations: [ - { - language: 'python', - description: t( - 'Raise an unhandled Python exception by inserting a divide by zero expression into your application:' - ), - code: 'division_by_zero = 1 / 0', - }, - ], - }, -]; -// Configuration End - -export function GettingStartedWithPython({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [` dsn="${dsn}",`]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } + dsn="${params.dsn}",${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } +)`; - sentryInitContent = sentryInitContent.concat(otherConfigs); +const onboarding: OnboardingConfig = { + install: () => [ + { + type: StepType.INSTALL, + description: tct('Install our Python SDK using [code:pip]:', { + code: <code />, + }), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: t( + "Import and initialize the Sentry SDK early in your application's setup:" + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + }, + ], + verify: () => [ + { + type: StepType.VERIFY, + description: t( + 'One way to verify your setup is by intentionally causing an error that breaks your application.' + ), + configurations: [ + { + language: 'python', + description: t( + 'Raise an unhandled Python exception by inserting a divide by zero expression into your application:' + ), + code: 'division_by_zero = 1 / 0', + }, + ], + }, + ], +}; - return ( - <Layout - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithPython; +export default docs; diff --git a/static/app/gettingStartedDocs/python/rq.spec.tsx b/static/app/gettingStartedDocs/python/rq.spec.tsx index d5b86b00645c18..d25c8f62fbe4b6 100644 --- a/static/app/gettingStartedDocs/python/rq.spec.tsx +++ b/static/app/gettingStartedDocs/python/rq.spec.tsx @@ -1,18 +1,42 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './rq'; -import {GettingStartedWithRq, steps} from './rq'; - -describe('GettingStartedWithRq', function () { +describe('rq onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithRq dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Job definition'})).toBeInTheDocument(); + expect( + screen.getByRole('heading', {name: 'Settings for worker'}) + ).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Main Python Script'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk\[rq\]/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/rq.tsx b/static/app/gettingStartedDocs/python/rq.tsx index 4b2f97a379a15a..d9310f0934a62d 100644 --- a/static/app/gettingStartedDocs/python/rq.tsx +++ b/static/app/gettingStartedDocs/python/rq.tsx @@ -1,122 +1,61 @@ +import {Fragment} from 'react'; + import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; +type Params = DocsParams; -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% - # of sampled transactions. - # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; +const getInitCallSnippet = (params: Params) => ` +sentry_sdk.init( + dsn="${params.dsn}",${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } +)`; -const introduction = ( - <p> - {tct('The RQ integration adds support for the [link:RQ Job Queue System].', { - link: <ExternalLink href="https://python-rq.org/" />, - })} - </p> -); - -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.CONFIGURE, - description: ( - <span> - <p> - {tct( - 'If you have the [codeRq:rq] package in your dependencies, the RQ integration will be enabled automatically when you initialize the Sentry SDK.', - { - codeRq: <code />, - } - )} - </p> - <p> - {tct('Create a file called [code:mysettings.py] with the following content:', { - code: <code />, - })} - </p> - </span> - ), - configurations: [ - { - language: 'python', - code: ` +const getSdkSetupSnippet = (params: Params) => ` # mysettings.py import sentry_sdk -sentry_sdk.init( -${sentryInitContent} -) - `, - }, - { - description: t('Start your worker with:'), - language: 'shell', - code: ` +${getInitCallSnippet(params)}`; + +const getStartWorkerSnippet = () => ` rq worker \ -c mysettings \ # module name of mysettings.py ---sentry-dsn="..." # only necessary for RQ < 1.0 - `, - }, - ], - additionalInfo: ( - <p> - {tct( - 'Generally, make sure that the call to [code:init] is loaded on worker startup, and not only in the module where your jobs are defined. Otherwise, the initialization happens too late and events might end up not being reported.', - {code: <code />} - )} - </p> - ), - }, - { - type: StepType.VERIFY, - description: ( - <p> - {' '} - {tct( - 'To verify, create a simple job and a [code:main.py] script that enqueues the job in RQ, then start an RQ worker to run the job:', - { - code: <code />, - } - )} - </p> - ), - configurations: [ - { - description: <h5>{t('Job definition')}</h5>, - language: 'python', - code: `# jobs.py +--sentry-dsn="..." # only necessary for RQ < 1.0`; + +const getJobDefinitionSnippet = () => `# jobs.py def hello(name): 1/0 # raises an error - return "Hello %s!" % name - `, - }, - { - description: <h5>{t('Settings for worker')}</h5>, - language: 'python', - code: `# mysettings.py + return "Hello %s!" % name`; + +const getWorkerSetupSnippet = (params: Params) => ` +# mysettings.py import sentry_sdk # Sentry configuration for RQ worker processes -sentry_sdk.init( -${sentryInitContent} -) - `, - }, - { - description: <h5>{t('Main Python Script')}</h5>, - language: 'python', - code: `# main.py +${getInitCallSnippet(params)}`; + +const getMainPythonScriptSetupSnippet = (params: Params) => ` +# main.py from redis import Redis from rq import Queue @@ -124,72 +63,132 @@ from jobs import hello import sentry_sdk -# Sentry configuration for main.py process (same as above) -sentry_sdk.init( -${sentryInitContent} -) +#import { get } from 'lodash'; +Sentry configuration for main.py process (same as above) +${getInitCallSnippet(params)} q = Queue(connection=Redis()) with sentry_sdk.start_transaction(name="testing_sentry"): - result = q.enqueue(hello, "World") - `, - }, - ], - additionalInfo: ( - <div> - <p> - {tct( - 'When you run [codeMain:python main.py] a transaction named [codeTrxName:testing_sentry] in the Performance section of Sentry will be created.', - { - codeMain: <code />, - codeTrxName: <code />, - } - )} - </p> - <p> - {tct( - 'If you run the RQ worker with [codeWorker:rq worker -c mysettings] a transaction for the execution of [codeFunction:hello()] will be created. Additionally, an error event will be sent to Sentry and will be connected to the transaction.', - { - codeWorker: <code />, - codeFunction: <code />, - } - )} - </p> - <p>{t('It takes a couple of moments for the data to appear in Sentry.')}</p> - </div> - ), - }, -]; -// Configuration End - -export function GettingStartedWithRq({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [` dsn="${dsn}",`]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } + result = q.enqueue(hello, "World")`; - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); - - return ( - <Layout - introduction={introduction} - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} - -export default GettingStartedWithRq; +const onboarding: OnboardingConfig = { + introduction: () => + tct('The RQ integration adds support for the [link:RQ Job Queue System].', { + link: <ExternalLink href="https://python-rq.org/" />, + }), + install: () => [ + { + type: StepType.INSTALL, + description: tct( + 'Install [code:sentry-sdk] from PyPI with the [sentryRQCode:rq] extra:', + { + code: <code />, + sentryRQCode: <code />, + } + ), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk[rq]', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: ( + <Fragment> + <p> + {tct( + 'If you have the [codeRq:rq] package in your dependencies, the RQ integration will be enabled automatically when you initialize the Sentry SDK.', + { + codeRq: <code />, + } + )} + </p> + <p> + {tct( + 'Create a file called [code:mysettings.py] with the following content:', + { + code: <code />, + } + )} + </p> + </Fragment> + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + { + description: t('Start your worker with:'), + language: 'shell', + code: getStartWorkerSnippet(), + }, + ], + additionalInfo: tct( + 'Generally, make sure that the call to [code:init] is loaded on worker startup, and not only in the module where your jobs are defined. Otherwise, the initialization happens too late and events might end up not being reported.', + {code: <code />} + ), + }, + ], + verify: params => [ + { + type: StepType.VERIFY, + description: tct( + 'To verify, create a simple job and a [code:main.py] script that enqueues the job in RQ, then start an RQ worker to run the job:', + { + code: <code />, + } + ), + configurations: [ + { + description: <h5>{t('Job definition')}</h5>, + language: 'python', + code: getJobDefinitionSnippet(), + }, + { + description: <h5>{t('Settings for worker')}</h5>, + language: 'python', + code: getWorkerSetupSnippet(params), + }, + { + description: <h5>{t('Main Python Script')}</h5>, + language: 'python', + code: getMainPythonScriptSetupSnippet(params), + }, + ], + additionalInfo: ( + <div> + <p> + {tct( + 'When you run [codeMain:python main.py] a transaction named [codeTrxName:testing_sentry] in the Performance section of Sentry will be created.', + { + codeMain: <code />, + codeTrxName: <code />, + } + )} + </p> + <p> + {tct( + 'If you run the RQ worker with [codeWorker:rq worker -c mysettings] a transaction for the execution of [codeFunction:hello()] will be created. Additionally, an error event will be sent to Sentry and will be connected to the transaction.', + { + codeWorker: <code />, + codeFunction: <code />, + } + )} + </p> + <p>{t('It takes a couple of moments for the data to appear in Sentry.')}</p> + </div> + ), + }, + ], +}; + +const docs: Docs = { + onboarding, +}; + +export default docs; diff --git a/static/app/gettingStartedDocs/python/serverless.spec.tsx b/static/app/gettingStartedDocs/python/serverless.spec.tsx index db7c53fd813f0e..4b6bfe34ac70e4 100644 --- a/static/app/gettingStartedDocs/python/serverless.spec.tsx +++ b/static/app/gettingStartedDocs/python/serverless.spec.tsx @@ -1,18 +1,37 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './serverless'; -import {GettingStartedWithServerless, steps} from './serverless'; - -describe('GettingStartedWithServerless', function () { +describe('serverless onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithServerless dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/serverless.tsx b/static/app/gettingStartedDocs/python/serverless.tsx index a99408cc7a2fbc..a5163a32d0394e 100644 --- a/static/app/gettingStartedDocs/python/serverless.tsx +++ b/static/app/gettingStartedDocs/python/serverless.tsx @@ -1,138 +1,123 @@ import {Fragment} from 'react'; import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; - -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% - # of sampled transactions. - # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; +type Params = DocsParams; -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <Fragment> - <p> - {tct( - 'It is recommended to use an [link:integration for your particular serverless environment if available], as those are easier to use and capture more useful information.', - { - link: ( - <ExternalLink href="https://docs.sentry.io/platforms/python/#serverless" /> - ), - } - )} - </p> - {t( - 'If you use a serverless provider not directly supported by the SDK, you can use this generic integration.' - )} - </Fragment> - ), - configurations: [ - { - language: 'python', - description: ( - <p> - {tct( - 'Apply the [code:serverless_function] decorator to each function that might throw errors:', - {code: <code />} - )} - </p> - ), - code: ` +const getSdkSetupSnippet = (params: Params) => ` import sentry_sdk from sentry_sdk.integrations.serverless import serverless_function sentry_sdk.init( -${sentryInitContent} + dsn="${params.dsn}",${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } ) @serverless_function -def my_function(...): ... - `, - }, - ], - }, - { - type: StepType.VERIFY, - description: ( - <p> - {tct( - 'Wrap a functions with the [code:serverless_function] that triggers an error:', - { - code: <code />, - } - )} - </p> - ), - configurations: [ - { - language: 'python', - code: `import sentry_sdk +def my_function(...): ...`; + +const getVerifySnippet = () => `import sentry_sdk from sentry_sdk.integrations.serverless import serverless_function -sentry_sdk.init( -${sentryInitContent} -) +sentry_sdk.init(...) # same as above @serverless_function def my_function(...): - 1/0 # raises an error - `, - }, - ], - additionalInfo: ( + 1/0 # raises an error`; + +const onboarding: OnboardingConfig = { + introduction: () => ( + <Fragment> <p> {tct( - 'Now deploy your function. When you now run your function an error event will be sent to Sentry.', - {} + 'It is recommended to use an [link:integration for your particular serverless environment if available], as those are easier to use and capture more useful information.', + { + link: ( + <ExternalLink href="https://docs.sentry.io/platforms/python/#serverless" /> + ), + } )} </p> - ), - }, -]; -// Configuration End - -export function GettingStartedWithServerless({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [` dsn="${dsn}",`]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); + {t( + 'If you use a serverless provider not directly supported by the SDK, you can use this generic integration.' + )} + </Fragment> + ), + install: () => [ + { + type: StepType.INSTALL, + description: tct('Install our Python SDK using [code:pip]:', { + code: <code />, + }), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk', + }, + ], + }, + ], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: tct( + 'Apply the [code:serverless_function] decorator to each function that might throw errors:', + {code: <code />} + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + }, + ], + verify: () => [ + { + type: StepType.VERIFY, + description: tct( + 'Wrap a functions with the [code:serverless_function] that triggers an error:', + { + code: <code />, + } + ), + configurations: [ + { + language: 'python', + code: getVerifySnippet(), + }, + ], + additionalInfo: tct( + 'Now deploy your function. When you now run your function an error event will be sent to Sentry.', + {} + ), + }, + ], +}; - return ( - <Layout - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithServerless; +export default docs; diff --git a/static/app/gettingStartedDocs/python/tryton.spec.tsx b/static/app/gettingStartedDocs/python/tryton.spec.tsx index e0cc086e99325a..0ae888de0adf8e 100644 --- a/static/app/gettingStartedDocs/python/tryton.spec.tsx +++ b/static/app/gettingStartedDocs/python/tryton.spec.tsx @@ -1,18 +1,30 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './django'; -import {GettingStartedWithTryton, steps} from './tryton'; - -describe('GettingStartedWithTryton', function () { +describe('django onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithTryton dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/tryton.tsx b/static/app/gettingStartedDocs/python/tryton.tsx index 7e26dbe07aa0ae..2273f5abdab484 100644 --- a/static/app/gettingStartedDocs/python/tryton.tsx +++ b/static/app/gettingStartedDocs/python/tryton.tsx @@ -1,58 +1,46 @@ import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -const introduction = ( - <p> - {tct('The Tryton integration adds support for the [link:Tryton Framework Server].', { - link: <ExternalLink href="https://www.tryton.org/" />, - })} - </p> -); +type Params = DocsParams; -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.CONFIGURE, - description: ( - <p> - {tct( - 'To configure the SDK, initialize it with the integration in a custom [code:wsgi.py] script:', - { - code: <code />, - } - )} - </p> - ), - configurations: [ - { - language: 'python', - code: `# wsgi.py +const getSdkSetupSnippet = (params: Params) => ` +# wsgi.py import sentry_sdk from sentry_sdk.integrations.trytond import TrytondWSGIIntegration sentry_sdk.init( - ${sentryInitContent} - ) + dsn="${params.dsn}", + integrations:[ + sentry_sdk.integrations.trytond.TrytondWSGIIntegration(), + ],${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } +) from trytond.application import app as application -# ... - `, - }, - { - description: t( - 'In Tryton>=5.4 an error handler can be registered to respond the client with a custom error message including the Sentry event id instead of a traceback.' - ), - language: 'python', - code: ` -# wsgi.py +# ...`; + +const getErrorHandlerSnippet = () => `# wsgi.py # ... from trytond.exceptions import TrytonException @@ -65,35 +53,43 @@ def _(app, request, e): else: event_id = sentry_sdk.last_event_id() data = UserError('Custom message', f'{event_id}{e}') - return app.make_response(request, data) - `, - }, - ], - }, -]; -// Configuration End - -export function GettingStartedWithTryton({dsn, ...props}: ModuleProps) { - const otherConfigs: string[] = []; + return app.make_response(request, data)`; - let sentryInitContent: string[] = [ - ` dsn="${dsn}",`, - ` integrations=[`, - ` sentry_sdk.integrations.trytond.TrytondWSGIIntegration(),`, - ` ],`, - ]; - - sentryInitContent = sentryInitContent.concat(otherConfigs); +const onboarding: OnboardingConfig = { + introduction: () => + tct('The Tryton integration adds support for the [link:Tryton Framework Server].', { + link: <ExternalLink href="https://www.tryton.org/" />, + }), + install: () => [], + configure: (params: Params) => [ + { + type: StepType.CONFIGURE, + description: tct( + 'To configure the SDK, initialize it with the integration in a custom [code:wsgi.py] script:', + { + code: <code />, + } + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + { + description: t( + 'In Tryton>=5.4 an error handler can be registered to respond the client with a custom error message including the Sentry event id instead of a traceback.' + ), + language: 'python', + code: getErrorHandlerSnippet(), + }, + ], + }, + ], + verify: () => [], +}; - return ( - <Layout - introduction={introduction} - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} +const docs: Docs = { + onboarding, +}; -export default GettingStartedWithTryton; +export default docs; diff --git a/static/app/gettingStartedDocs/python/wsgi.spec.tsx b/static/app/gettingStartedDocs/python/wsgi.spec.tsx index bbad5e37cf7265..94bd5371f57882 100644 --- a/static/app/gettingStartedDocs/python/wsgi.spec.tsx +++ b/static/app/gettingStartedDocs/python/wsgi.spec.tsx @@ -1,18 +1,37 @@ -import {render, screen} from 'sentry-test/reactTestingLibrary'; +import {renderWithOnboardingLayout} from 'sentry-test/onboarding/renderWithOnboardingLayout'; +import {screen} from 'sentry-test/reactTestingLibrary'; +import {textWithMarkupMatcher} from 'sentry-test/utils'; -import {StepTitle} from 'sentry/components/onboarding/gettingStartedDoc/step'; +import docs from './wsgi'; -import {GettingStartedWithWSGI, steps} from './wsgi'; - -describe('GettingStartedWithWSGI', function () { +describe('wsgi onboarding docs', function () { it('renders doc correctly', function () { - render(<GettingStartedWithWSGI dsn="test-dsn" projectSlug="test-project" />); + renderWithOnboardingLayout(docs); + + // Renders main headings + expect(screen.getByRole('heading', {name: 'Install'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Configure SDK'})).toBeInTheDocument(); + expect(screen.getByRole('heading', {name: 'Verify'})).toBeInTheDocument(); + + // Renders install instructions + expect( + screen.getByText(textWithMarkupMatcher(/pip install --upgrade sentry-sdk/)) + ).toBeInTheDocument(); + }); + + it('renders without performance monitoring', function () { + renderWithOnboardingLayout(docs, { + selectedProducts: [], + }); + + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/traces_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); - // Steps - for (const step of steps({sentryInitContent: 'test-init-content'})) { - expect( - screen.getByRole('heading', {name: step.title ?? StepTitle[step.type]}) - ).toBeInTheDocument(); - } + // Does not render config option + expect( + screen.queryByText(textWithMarkupMatcher(/profiles_sample_rate: 1\.0,/)) + ).not.toBeInTheDocument(); }); }); diff --git a/static/app/gettingStartedDocs/python/wsgi.tsx b/static/app/gettingStartedDocs/python/wsgi.tsx index bf6c853c5de19d..b25152317de7c6 100644 --- a/static/app/gettingStartedDocs/python/wsgi.tsx +++ b/static/app/gettingStartedDocs/python/wsgi.tsx @@ -1,78 +1,48 @@ import {Fragment} from 'react'; import ExternalLink from 'sentry/components/links/externalLink'; -import {Layout, LayoutProps} from 'sentry/components/onboarding/gettingStartedDoc/layout'; -import {ModuleProps} from 'sentry/components/onboarding/gettingStartedDoc/sdkDocumentation'; import {StepType} from 'sentry/components/onboarding/gettingStartedDoc/step'; -import {ProductSolution} from 'sentry/components/onboarding/productSelection'; +import type { + Docs, + DocsParams, + OnboardingConfig, +} from 'sentry/components/onboarding/gettingStartedDoc/types'; import {t, tct} from 'sentry/locale'; -// Configuration Start -const performanceConfiguration = ` # Set traces_sample_rate to 1.0 to capture 100% - # of transactions for performance monitoring. - traces_sample_rate=1.0,`; - -const profilingConfiguration = ` # Set profiles_sample_rate to 1.0 to profile 100% - # of sampled transactions. - # We recommend adjusting this value in production. - profiles_sample_rate=1.0,`; +type Params = DocsParams; -export const steps = ({ - sentryInitContent, -}: { - sentryInitContent: string; -}): LayoutProps['steps'] => [ - { - type: StepType.INSTALL, - description: ( - <Fragment> - <p> - {tct( - 'It is recommended to use an [link:integration for your particular WSGI framework if available], as those are easier to use and capture more useful information.', - { - link: ( - <ExternalLink href="https://docs.sentry.io/platforms/python/#web-frameworks" /> - ), - } - )} - </p> - {t( - 'If you use a WSGI framework not directly supported by the SDK, or wrote a raw WSGI app, you can use this generic WSGI middleware. It captures errors and attaches a basic amount of information for incoming requests.' - )} - </Fragment> - ), - configurations: [ - { - language: 'python', - code: ` +const getSdkSetupSnippet = (params: Params) => ` import sentry_sdk from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware from my_wsgi_app import app sentry_sdk.init( -${sentryInitContent} + dsn="${params.dsn}",${ + params.isPerformanceSelected + ? ` + # Set traces_sample_rate to 1.0 to capture 100% + # of transactions for performance monitoring. + traces_sample_rate=1.0,` + : '' + }${ + params.isProfilingSelected + ? ` + # Set profiles_sample_rate to 1.0 to profile 100% + # of sampled transactions. + # We recommend adjusting this value in production. + profiles_sample_rate=1.0,` + : '' + } ) -app = SentryWsgiMiddleware(app) - `, - }, - ], - }, - { - type: StepType.VERIFY, - description: t( - 'You can easily verify your Sentry installation by creating a route that triggers an error:' - ), - configurations: [ - { - language: 'python', - code: `import sentry_sdk +app = SentryWsgiMiddleware(app)`; + +const getVerifySnippet = () => ` +import sentry_sdk from sentry_sdk.integrations.wsgi import SentryWsgiMiddleware -sentry_sdk.init( -${sentryInitContent} -) +sentry_sdk.init(...) # same as above def app(env, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) @@ -84,58 +54,92 @@ app = SentryWsgiMiddleware(app) # Run the application in a mini WSGI server. from wsgiref.simple_server import make_server -make_server('', 8000, app).serve_forever() - `, - }, - ], - additionalInfo: ( - <div> - <p> - {tct( - 'When you point your browser to [link:http://localhost:8000/] a transaction in the Performance section of Sentry will be created.', - { - link: <ExternalLink href="http://localhost:8000/" />, - } - )} - </p> - <p> - {t( - 'Additionally, an error event will be sent to Sentry and will be connected to the transaction.' - )} - </p> - <p>{t('It takes a couple of moments for the data to appear in Sentry.')}</p> - </div> - ), - }, -]; -// Configuration End - -export function GettingStartedWithWSGI({ - dsn, - activeProductSelection = [], - ...props -}: ModuleProps) { - const otherConfigs: string[] = []; - - let sentryInitContent: string[] = [` dsn="${dsn}",`]; - - if (activeProductSelection.includes(ProductSolution.PERFORMANCE_MONITORING)) { - otherConfigs.push(performanceConfiguration); - } - - if (activeProductSelection.includes(ProductSolution.PROFILING)) { - otherConfigs.push(profilingConfiguration); - } - - sentryInitContent = sentryInitContent.concat(otherConfigs); - - return ( - <Layout - steps={steps({ - sentryInitContent: sentryInitContent.join('\n'), - })} - {...props} - /> - ); -} -export default GettingStartedWithWSGI; +make_server('', 8000, app).serve_forever()`; + +const onboarding: OnboardingConfig = { + introduction: () => ( + <Fragment> + <p> + {tct( + 'It is recommended to use an [link:integration for your particular WSGI framework if available], as those are easier to use and capture more useful information.', + { + link: ( + <ExternalLink href="https://docs.sentry.io/platforms/python/#web-frameworks" /> + ), + } + )} + </p> + <p> + {t( + 'If you use a WSGI framework not directly supported by the SDK, or wrote a raw WSGI app, you can use this generic WSGI middleware. It captures errors and attaches a basic amount of information for incoming requests.' + )} + </p> + </Fragment> + ), + install: () => [ + { + type: StepType.INSTALL, + description: tct('Install our Python SDK using [code:pip]:', { + code: <code />, + }), + configurations: [ + { + language: 'bash', + code: 'pip install --upgrade sentry-sdk', + }, + ], + }, + ], + configure: params => [ + { + type: StepType.CONFIGURE, + description: t( + 'Then you can use this generic WSGI middleware. It captures errors and attaches a basic amount of information for incoming requests.' + ), + configurations: [ + { + language: 'python', + code: getSdkSetupSnippet(params), + }, + ], + }, + ], + verify: () => [ + { + type: StepType.VERIFY, + description: t( + 'You can easily verify your Sentry installation by creating a route that triggers an error:' + ), + configurations: [ + { + language: 'python', + code: getVerifySnippet(), + }, + ], + additionalInfo: ( + <Fragment> + <p> + {tct( + 'When you point your browser to [link:http://localhost:8000/] a transaction in the Performance section of Sentry will be created.', + { + link: <ExternalLink href="http://localhost:8000/" />, + } + )} + </p> + <p> + {t( + 'Additionally, an error event will be sent to Sentry and will be connected to the transaction.' + )} + </p> + <p>{t('It takes a couple of moments for the data to appear in Sentry.')}</p> + </Fragment> + ), + }, + ], +}; + +const docs: Docs = { + onboarding, +}; + +export default docs;
d13c99344a03aaffb45774733f8c6359bb23a68a
2023-07-14 22:55:29
Julia Hoge
ref(ui): Change wording of stacktrace order in user settings (#52889)
false
Change wording of stacktrace order in user settings (#52889)
ref
diff --git a/static/app/data/forms/accountPreferences.tsx b/static/app/data/forms/accountPreferences.tsx index 051ebcf2009cbd..5280eac789b95e 100644 --- a/static/app/data/forms/accountPreferences.tsx +++ b/static/app/data/forms/accountPreferences.tsx @@ -54,9 +54,9 @@ const formGroups: JsonFormObject[] = [ type: 'select', required: false, options: [ - {value: -1, label: t('Default (let Sentry decide)')}, - {value: 1, label: t('Most recent call last')}, - {value: 2, label: t('Most recent call first')}, + {value: -1, label: t('Default')}, + {value: 1, label: t('Oldest')}, + {value: 2, label: t('Newest')}, ], label: t('Stack Trace Order'), help: t('Choose the default ordering of frames in stack traces'),
bf6f5101ca83fcdb1a5d8f70d534d810b5a45b2d
2023-11-09 04:24:24
Dominik Buszowiecki
feat(browser-starfish): add resource summary charts, remove image tabs (#59628)
false
add resource summary charts, remove image tabs (#59628)
feat
diff --git a/static/app/utils/discover/fields.tsx b/static/app/utils/discover/fields.tsx index 43513bb9a2c009..1ad9f524695263 100644 --- a/static/app/utils/discover/fields.tsx +++ b/static/app/utils/discover/fields.tsx @@ -137,6 +137,12 @@ export const RATE_UNIT_LABELS = { [RateUnits.PER_HOUR]: '/hr', }; +export const RATE_UNIT_TITLE = { + [RateUnits.PER_SECOND]: 'Per Second', + [RateUnits.PER_MINUTE]: 'Per Minute', + [RateUnits.PER_HOUR]: 'Per Hour', +}; + const CONDITIONS_ARGUMENTS: SelectValue<string>[] = [ { label: 'is equal to', diff --git a/static/app/views/performance/browser/resources/index.tsx b/static/app/views/performance/browser/resources/index.tsx index fecc06cf9c890f..d36910adb78bc6 100644 --- a/static/app/views/performance/browser/resources/index.tsx +++ b/static/app/views/performance/browser/resources/index.tsx @@ -1,4 +1,3 @@ -import {browserHistory} from 'react-router'; import styled from '@emotion/styled'; import Breadcrumbs from 'sentry/components/breadcrumbs'; @@ -7,25 +6,29 @@ import * as Layout from 'sentry/components/layouts/thirds'; import {DatePageFilter} from 'sentry/components/organizations/datePageFilter'; import PageFilterBar from 'sentry/components/organizations/pageFilterBar'; import {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter'; -import {TabList, Tabs} from 'sentry/components/tabs'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import {useLocation} from 'sentry/utils/useLocation'; +import {RateUnits} from 'sentry/utils/discover/fields'; import useOrganization from 'sentry/utils/useOrganization'; import {normalizeUrl} from 'sentry/utils/withDomainRequired'; import ImageView from 'sentry/views/performance/browser/resources/imageView'; -import JSCSSView from 'sentry/views/performance/browser/resources/jsCssView'; +import JSCSSView, { + DEFAULT_RESOURCE_TYPES, + FilterOptionsContainer, +} from 'sentry/views/performance/browser/resources/jsCssView'; +import DomainSelector from 'sentry/views/performance/browser/resources/shared/domainSelector'; import { BrowserStarfishFields, useResourceModuleFilters, } from 'sentry/views/performance/browser/resources/utils/useResourceFilters'; import {ModulePageProviders} from 'sentry/views/performance/database/modulePageProviders'; -const {SPAN_OP} = BrowserStarfishFields; +const {SPAN_OP, SPAN_DOMAIN} = BrowserStarfishFields; + +export const RESOURCE_THROUGHPUT_UNIT = RateUnits.PER_MINUTE; function ResourcesLandingPage() { const organization = useOrganization(); - const location = useLocation(); const filters = useResourceModuleFilters(); return ( @@ -53,33 +56,20 @@ function ResourcesLandingPage() { <FeatureBadge type="alpha" /> </Layout.Title> </Layout.HeaderContent> - <StyledTabs> - <TabList - hideBorder - onSelectionChange={key => { - browserHistory.push({ - ...location, - query: { - ...location.query, - [SPAN_OP]: key, - }, - }); - }} - > - <TabList.Item key="">{t('JS/CSS/Fonts')}</TabList.Item> - <TabList.Item key="resource.img">{t('Images')}</TabList.Item> - </TabList> - </StyledTabs> </Layout.Header> <Layout.Body> <Layout.Main fullWidth> - <PaddedContainer> + <FilterOptionsContainer> <PageFilterBar condensed> <ProjectPageFilter /> <DatePageFilter /> </PageFilterBar> - </PaddedContainer> + <DomainSelector + value={filters[SPAN_DOMAIN] || ''} + defaultResourceTypes={DEFAULT_RESOURCE_TYPES} + /> + </FilterOptionsContainer> {(!filters[SPAN_OP] || filters[SPAN_OP] === 'resource.script' || @@ -96,8 +86,4 @@ export const PaddedContainer = styled('div')` margin-bottom: ${space(2)}; `; -const StyledTabs = styled(Tabs)` - grid-column: 1/-1; -`; - export default ResourcesLandingPage; diff --git a/static/app/views/performance/browser/resources/jsCssView/index.tsx b/static/app/views/performance/browser/resources/jsCssView/index.tsx index d27031293c22eb..c5df47aab6b8d3 100644 --- a/static/app/views/performance/browser/resources/jsCssView/index.tsx +++ b/static/app/views/performance/browser/resources/jsCssView/index.tsx @@ -6,8 +6,8 @@ import SwitchButton from 'sentry/components/switchButton'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; import {useLocation} from 'sentry/utils/useLocation'; +import {RESOURCE_THROUGHPUT_UNIT} from 'sentry/views/performance/browser/resources'; import ResourceTable from 'sentry/views/performance/browser/resources/jsCssView/resourceTable'; -import DomainSelector from 'sentry/views/performance/browser/resources/shared/domainSelector'; import SelectControlWithProps from 'sentry/views/performance/browser/resources/shared/selectControlWithProps'; import { BrowserStarfishFields, @@ -15,6 +15,9 @@ import { } from 'sentry/views/performance/browser/resources/utils/useResourceFilters'; import {useResourcePagesQuery} from 'sentry/views/performance/browser/resources/utils/useResourcePagesQuery'; import {useResourceSort} from 'sentry/views/performance/browser/resources/utils/useResourceSort'; +import {ModuleName} from 'sentry/views/starfish/types'; +import {SpanTimeCharts} from 'sentry/views/starfish/views/spans/spanTimeCharts'; +import {ModuleFilters} from 'sentry/views/starfish/views/spans/useModuleFilters'; const { SPAN_OP: RESOURCE_TYPE, @@ -23,7 +26,7 @@ const { RESOURCE_RENDER_BLOCKING_STATUS, } = BrowserStarfishFields; -const DEFAULT_RESOURCE_TYPES = ['resource.script', 'resource.css']; +export const DEFAULT_RESOURCE_TYPES = ['resource.script', 'resource.css']; type Option = { label: string; @@ -35,6 +38,11 @@ function JSCSSView() { const sort = useResourceSort(); const location = useLocation(); + const spanTimeChartsFilters: ModuleFilters = { + 'span.op': `[${DEFAULT_RESOURCE_TYPES.join(',')}]`, + ...(filters[SPAN_DOMAIN] ? {[SPAN_DOMAIN]: filters[SPAN_DOMAIN]} : {}), + }; + const handleBlockingToggle: MouseEventHandler = () => { const hasBlocking = filters[RESOURCE_RENDER_BLOCKING_STATUS] === 'blocking'; const newBlocking = hasBlocking ? undefined : 'blocking'; @@ -49,11 +57,13 @@ function JSCSSView() { return ( <Fragment> + <SpanTimeCharts + moduleName={ModuleName.OTHER} + appliedFilters={spanTimeChartsFilters} + throughputUnit={RESOURCE_THROUGHPUT_UNIT} + /> + <FilterOptionsContainer> - <DomainSelector - value={filters[SPAN_DOMAIN] || ''} - defaultResourceTypes={DEFAULT_RESOURCE_TYPES} - /> <ResourceTypeSelector value={filters[RESOURCE_TYPE] || ''} /> <PageSelector value={filters[TRANSACTION] || ''} diff --git a/static/app/views/starfish/views/spans/spanTimeCharts.tsx b/static/app/views/starfish/views/spans/spanTimeCharts.tsx index 152e946df1540c..e3bc3182a1a6ab 100644 --- a/static/app/views/starfish/views/spans/spanTimeCharts.tsx +++ b/static/app/views/starfish/views/spans/spanTimeCharts.tsx @@ -16,6 +16,7 @@ import {ModuleName, SpanMetricsField} from 'sentry/views/starfish/types'; import {STARFISH_CHART_INTERVAL_FIDELITY} from 'sentry/views/starfish/utils/constants'; import {useSpansQuery} from 'sentry/views/starfish/utils/useSpansQuery'; import {useErrorRateQuery as useErrorCountQuery} from 'sentry/views/starfish/views/spans/queries'; +import {EMPTY_OPTION_VALUE} from 'sentry/views/starfish/views/spans/selectors/emptyOption'; import { DataTitles, getDurationChartTitle, @@ -24,7 +25,7 @@ import { import {ModuleFilters} from 'sentry/views/starfish/views/spans/useModuleFilters'; import {NULL_SPAN_CATEGORY} from 'sentry/views/starfish/views/webServiceView/spanGroupBreakdownContainer'; -const {SPAN_SELF_TIME, SPAN_MODULE, SPAN_DESCRIPTION} = SpanMetricsField; +const {SPAN_SELF_TIME, SPAN_MODULE, SPAN_DESCRIPTION, SPAN_DOMAIN} = SpanMetricsField; const CHART_HEIGHT = 140; @@ -32,18 +33,25 @@ type Props = { appliedFilters: ModuleFilters; moduleName: ModuleName; spanCategory?: string; + throughputUnit?: RateUnits; }; type ChartProps = { filters: ModuleFilters; moduleName: ModuleName; + throughtputUnit: RateUnits; }; function getSegmentLabel(moduleName: ModuleName) { return moduleName === ModuleName.DB ? 'Queries' : 'Requests'; } -export function SpanTimeCharts({moduleName, appliedFilters, spanCategory}: Props) { +export function SpanTimeCharts({ + moduleName, + appliedFilters, + spanCategory, + throughputUnit = RateUnits.PER_MINUTE, +}: Props) { const {selection} = usePageFilters(); const eventView = getEventView(moduleName, selection, appliedFilters, spanCategory); @@ -61,7 +69,7 @@ export function SpanTimeCharts({moduleName, appliedFilters, spanCategory}: Props {Comp: (props: ChartProps) => JSX.Element; title: string}[] > = { [ModuleName.ALL]: [ - {title: getThroughputChartTitle(moduleName), Comp: ThroughputChart}, + {title: getThroughputChartTitle(moduleName, throughputUnit), Comp: ThroughputChart}, {title: getDurationChartTitle(moduleName), Comp: DurationChart}, ], [ModuleName.DB]: [], @@ -79,7 +87,11 @@ export function SpanTimeCharts({moduleName, appliedFilters, spanCategory}: Props {charts.map(({title, Comp}) => ( <ChartsContainerItem key={title}> <ChartPanel title={title}> - <Comp moduleName={moduleName} filters={appliedFilters} /> + <Comp + moduleName={moduleName} + filters={appliedFilters} + throughtputUnit={throughputUnit} + /> </ChartPanel> </ChartsContainerItem> ))} @@ -87,7 +99,11 @@ export function SpanTimeCharts({moduleName, appliedFilters, spanCategory}: Props ); } -function ThroughputChart({moduleName, filters}: ChartProps): JSX.Element { +function ThroughputChart({ + moduleName, + filters, + throughtputUnit, +}: ChartProps): JSX.Element { const pageFilters = usePageFilters(); const eventView = getEventView(moduleName, pageFilters.selection, filters); @@ -108,10 +124,17 @@ function ThroughputChart({moduleName, filters}: ChartProps): JSX.Element { const throughputTimeSeries = Object.keys(dataByGroup).map(groupName => { const groupData = dataByGroup[groupName]; + let throughputMultiplier = 1; // We're fetching per minute, so default is 1 + if (throughtputUnit === RateUnits.PER_SECOND) { + throughputMultiplier = 1 / 60; + } else if (throughtputUnit === RateUnits.PER_HOUR) { + throughputMultiplier = 60; + } + return { seriesName: label ?? 'Throughput', data: (groupData ?? []).map(datum => ({ - value: datum['spm()'], + value: datum['spm()'] * throughputMultiplier, name: datum.interval, })), }; @@ -131,12 +154,12 @@ function ThroughputChart({moduleName, filters}: ChartProps): JSX.Element { }} definedAxisTicks={4} aggregateOutputFormat="rate" - rateUnit={RateUnits.PER_MINUTE} + rateUnit={throughtputUnit} stacked isLineChart chartColors={[THROUGHPUT_COLOR]} tooltipFormatterOptions={{ - valueFormatter: value => formatRate(value, RateUnits.PER_MINUTE), + valueFormatter: value => formatRate(value, throughtputUnit), }} /> ); @@ -227,7 +250,7 @@ function ErrorChart({moduleName, filters}: ChartProps): JSX.Element { ); } -const SPAN_FILTER_KEYS = ['span_operation', 'domain', 'action']; +const SPAN_FILTER_KEYS = ['span_operation', SPAN_DOMAIN, 'action']; const getEventView = ( moduleName: ModuleName, @@ -260,7 +283,11 @@ const buildDiscoverQueryConditions = ( .filter(key => SPAN_FILTER_KEYS.includes(key)) .filter(key => Boolean(appliedFilters[key])) .map(key => { - return `${key}:${appliedFilters[key]}`; + const value = appliedFilters[key]; + if (key === SPAN_DOMAIN && value === EMPTY_OPTION_VALUE) { + return [`!has:${SPAN_DOMAIN}`]; + } + return `${key}:${value}`; }); result.push(`has:${SPAN_DESCRIPTION}`); diff --git a/static/app/views/starfish/views/spans/types.tsx b/static/app/views/starfish/views/spans/types.tsx index 552cd388737272..10b496c00c82aa 100644 --- a/static/app/views/starfish/views/spans/types.tsx +++ b/static/app/views/starfish/views/spans/types.tsx @@ -1,5 +1,6 @@ import {t} from 'sentry/locale'; import {defined} from 'sentry/utils'; +import {RATE_UNIT_TITLE, RateUnits} from 'sentry/utils/discover/fields'; export type DataKey = | 'change' @@ -38,12 +39,15 @@ export const DataTitles: Record<DataKey, string> = { 'avg(http.response_transfer_size)': t('Avg Transfer Size'), }; -export const getThroughputTitle = (spanOp?: string) => { +export const getThroughputTitle = ( + spanOp?: string, + throughputUnit = RateUnits.PER_MINUTE +) => { if (spanOp?.startsWith('db')) { - return t('Queries Per Min'); + return `${t('Queries')} ${RATE_UNIT_TITLE[throughputUnit]}`; } if (defined(spanOp)) { - return t('Requests Per Sec'); + return `${t('Requests')} ${RATE_UNIT_TITLE[throughputUnit]}`; } return '--'; }; @@ -56,12 +60,15 @@ export const getDurationChartTitle = (spanOp?: string) => { return '--'; }; -export const getThroughputChartTitle = (spanOp?: string) => { +export const getThroughputChartTitle = ( + spanOp?: string, + throughputUnit = RateUnits.PER_MINUTE +) => { if (spanOp?.startsWith('db')) { - return t('Queries Per Minute'); + return `${t('Queries')} ${RATE_UNIT_TITLE[throughputUnit]}`; } if (spanOp) { - return t('Requests Per Minute'); + return `${t('Requests')} ${RATE_UNIT_TITLE[throughputUnit]}`; } return '--'; };
0dc3422154b5e56dd7956ea45b593e9cdfa651cb
2018-04-06 03:47:36
Billy Vong
feat(ui): Add descriptions to settings routes (#7902)
false
Add descriptions to settings routes (#7902)
feat
diff --git a/src/sentry/static/sentry/app/views/settings/account/navigationConfiguration.jsx b/src/sentry/static/sentry/app/views/settings/account/navigationConfiguration.jsx index b43b1a80e69f7f..fad65de269a339 100644 --- a/src/sentry/static/sentry/app/views/settings/account/navigationConfiguration.jsx +++ b/src/sentry/static/sentry/app/views/settings/account/navigationConfiguration.jsx @@ -9,34 +9,50 @@ const accountNavigation = [ { path: `${pathPrefix}/details/`, title: t('Account Details'), + description: t('Change your account details and preferences'), }, { path: `${pathPrefix}/security/`, title: t('Security'), + description: t('Change your account password and/or two factor authentication'), }, { path: `${pathPrefix}/notifications/`, title: t('Notifications'), + description: t('Configure what email notifications to receive'), }, { path: `${pathPrefix}/emails/`, title: t('Emails'), + description: t( + 'Add or remove secondary emails, change your primary email, verify your emails' + ), }, { path: `${pathPrefix}/subscriptions/`, title: t('Subscriptions'), + description: t( + 'Change Sentry marketing subscriptions you are subscribed to (GDPR)' + ), }, { path: `${pathPrefix}/authorizations/`, title: t('Authorized Applications'), + description: t( + 'Manage third-party applications that have access to your Sentry account' + ), }, { path: `${pathPrefix}/identities/`, title: t('Identities'), + description: t( + 'Manage your third-party identities that are associated to Sentry' + ), }, { path: `${pathPrefix}/close-account/`, title: t('Close Account'), + description: t('Permanently close your Sentry account'), }, ], }, @@ -46,10 +62,14 @@ const accountNavigation = [ { path: `${pathPrefix}/api/applications/`, title: t('Applications'), + description: t('Add and configure OAuth2 applications'), }, { path: `${pathPrefix}/api/auth-tokens/`, title: t('Auth Tokens'), + description: t( + "Authentication tokens allow you to perform actions against the Sentry API on behalf of your account. They're the easiest way to get started using the API." + ), }, ], }, diff --git a/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.jsx b/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.jsx index 559a606c446d04..ec9c5dcd22cb9e 100644 --- a/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.jsx +++ b/src/sentry/static/sentry/app/views/settings/organization/navigationConfiguration.jsx @@ -11,14 +11,17 @@ const organizationNavigation = [ title: t('General Settings'), index: true, show: ({access}) => access.has('org:write'), + description: t('Configure general settings for an organization'), }, { path: `${pathPrefix}/projects/`, title: t('Projects'), + description: t("View and manage an organization's projects"), }, { path: `${pathPrefix}/teams/`, title: t('Teams'), + description: t("Manage an organization's teams"), }, { path: `${pathPrefix}/members/`, @@ -31,11 +34,13 @@ const organizationNavigation = [ return `${organization.pendingAccessRequests}`; }, show: ({access}) => access.has('member:read'), + description: t('Manage user membership for an organization'), }, { path: `${pathPrefix}/auth/`, title: t('Auth'), show: ({access, features}) => features.has('sso') && access.has('org:admin'), + description: t('Configure single sign-on'), }, { path: `${pathPrefix}/api-keys/`, @@ -46,16 +51,19 @@ const organizationNavigation = [ path: `${pathPrefix}/audit-log/`, title: t('Audit Log'), show: ({access}) => access.has('org:write'), + description: t('View the audit log for an organization'), }, { path: `${pathPrefix}/rate-limits/`, title: t('Rate Limits'), show: ({access}) => access.has('org:write'), + description: t('Configure rate limits for all projects in the organization'), }, { path: `${pathPrefix}/repos/`, title: t('Repositories'), show: ({access}) => access.has('org:write'), + description: t('Manage repositories connected to the organization'), }, ], }, diff --git a/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.jsx b/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.jsx index d3f52d5e50ed1f..9888abf03ad48c 100644 --- a/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.jsx +++ b/src/sentry/static/sentry/app/views/settings/project/navigationConfiguration.jsx @@ -13,27 +13,33 @@ export default function getConfiguration({project}) { path: `${pathPrefix}/`, index: true, title: t('General Settings'), + description: t('Configure general settings for a project'), }, { path: `${pathPrefix}/teams/`, title: t('Teams'), + description: t('Manage team access for a project'), }, { path: `${pathPrefix}/alerts/`, title: t('Alerts'), + description: t('Manage alerts and alert rules for a project'), }, { path: `${pathPrefix}/quotas/`, title: t('Rate Limits'), show: ({features}) => features.has('quotas'), + description: t("Configure project's rate limits"), }, { path: `${pathPrefix}/tags/`, title: t('Tags'), + description: t("View and manage a project's tags"), }, { path: `${pathPrefix}/environments/`, title: t('Environments'), + description: t('Manage environments in a project'), }, { path: `${pathPrefix}/issue-tracking/`, @@ -47,6 +53,7 @@ export default function getConfiguration({project}) { { path: `${pathPrefix}/ownership/`, title: t('Issue Ownership'), + description: t('Manage code ownership rules for a project'), }, { path: `${pathPrefix}/data-forwarding/`, @@ -55,6 +62,7 @@ export default function getConfiguration({project}) { { path: `${pathPrefix}/saved-searches/`, title: t('Saved Searches'), + description: t('Manage saved searches for a project and your account'), }, { path: `${pathPrefix}/debug-symbols/`, @@ -85,14 +93,19 @@ export default function getConfiguration({project}) { { path: `${pathPrefix}/user-feedback/`, title: t('User Feedback'), + description: t('Configure user feedback reporting feature'), }, { path: `${pathPrefix}/filters/`, title: t('Inbound Filters'), + description: t( + "Configure a project's inbound filters (e.g. browsers, messages)" + ), }, { path: `${pathPrefix}/keys/`, title: t('Client Keys (DSN)'), + description: t("View and manage the project's client keys (DSN)"), }, ], }, @@ -102,6 +115,7 @@ export default function getConfiguration({project}) { { path: `${pathPrefix}/plugins/`, title: t('All Integrations'), + description: t('View, enable, and disable all integrations for a project'), }, ...plugins.map(plugin => ({ path: `${pathPrefix}/plugins/${plugin.id}/`,
d4da14d6c9f94f74d4a93eb7088141560c8670dd
2019-10-09 05:02:19
Evan Purkhiser
ref(select-control): Add noMenu prop + minor focus cleanup (#14880)
false
Add noMenu prop + minor focus cleanup (#14880)
ref
diff --git a/src/sentry/static/sentry/app/components/forms/selectControl.jsx b/src/sentry/static/sentry/app/components/forms/selectControl.jsx index 468b5baf094686..b33ffda062ddd6 100644 --- a/src/sentry/static/sentry/app/components/forms/selectControl.jsx +++ b/src/sentry/static/sentry/app/components/forms/selectControl.jsx @@ -1,7 +1,7 @@ import PropTypes from 'prop-types'; import React from 'react'; import ReactSelect, {Async, Creatable, AsyncCreatable} from 'react-select'; -import styled from 'react-emotion'; +import styled, {css} from 'react-emotion'; import convertFromSelect2Choices from 'app/utils/convertFromSelect2Choices'; @@ -28,6 +28,8 @@ export default class SelectControl extends React.Component { multiple: PropTypes.bool, // multi is supported for compatibility multi: PropTypes.bool, + // disable rendering a menu + noMenu: PropTypes.bool, choices: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.array])), PropTypes.func, @@ -45,7 +47,7 @@ export default class SelectControl extends React.Component { }; render() { - const {async, creatable, options, choices, clearable, ...props} = this.props; + const {async, creatable, options, choices, clearable, noMenu, ...props} = this.props; // Compatibility with old select2 API const choicesOrOptions = @@ -53,6 +55,13 @@ export default class SelectControl extends React.Component { typeof choices === 'function' ? choices(this.props) : choices ) || options; + const noMenuProps = { + arrowRenderer: () => null, + menuRenderer: () => null, + openOnClick: false, + menuContainerStyle: {display: 'none'}, + }; + // "-Removes" props should match `clearable` unless explicitly defined in props // rest props should be after "-Removes" so that it can be overridden return ( @@ -63,6 +72,8 @@ export default class SelectControl extends React.Component { clearable={clearable} backspaceRemoves={clearable} deleteRemoves={clearable} + noMenu={noMenu} + {...(noMenu ? noMenuProps : {})} {...props} multi={this.props.multiple || this.props.multi} options={choicesOrOptions} @@ -98,13 +109,23 @@ forwardRef.displayName = 'SelectPicker'; const StyledSelect = styled(React.forwardRef(forwardRef))` font-size: 15px; - .Select-control, - &.Select.is-focused:not(.is-open) > .Select-control { + .Select-control { + border: 1px solid ${p => p.theme.borderDark}; height: ${p => p.height}px; overflow: visible; + } + + &.Select.is-focused > .Select-control { border: 1px solid ${p => p.theme.borderDark}; - box-shadow: inset ${p => p.theme.dropShadowLight}; + border-color: ${p => p.theme.gray}; + box-shadow: rgba(209, 202, 216, 0.5) 0 0 0 3px; } + + &.Select.is-focused:not(.is-open) > .Select-control { + height: ${p => p.height}px; + overflow: visible; + } + .Select-input { height: ${p => p.height}px; input { @@ -113,6 +134,10 @@ const StyledSelect = styled(React.forwardRef(forwardRef))` } } + &.Select--multi .Select-value { + margin-top: 6px; + } + .Select-placeholder, &.Select--single > .Select-control .Select-value { height: ${p => p.height}px; @@ -136,9 +161,15 @@ const StyledSelect = styled(React.forwardRef(forwardRef))` } } - /* stylelint-disable-next-line no-descending-specificity */ - &.Select.is-focused:not(.is-open) > .Select-control { - border-color: ${p => p.theme.gray}; - box-shadow: rgba(209, 202, 216, 0.5) 0 0 0 3px; + .Select-clear { + vertical-align: middle; } + + ${({noMenu}) => + noMenu && + css` + &.Select.is-focused.is-open > .Select-control { + border-radius: 4px; + } + `} `; diff --git a/tests/js/spec/components/__snapshots__/createProject.spec.jsx.snap b/tests/js/spec/components/__snapshots__/createProject.spec.jsx.snap index 19dcfc58b29070..698f16b07d58bf 100644 --- a/tests/js/spec/components/__snapshots__/createProject.spec.jsx.snap +++ b/tests/js/spec/components/__snapshots__/createProject.spec.jsx.snap @@ -1307,7 +1307,7 @@ exports[`CreateProject should deal with incorrect platform name if its provided <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} height={36} @@ -1321,7 +1321,7 @@ exports[`CreateProject should deal with incorrect platform name if its provided <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} forwardedRef={null} @@ -1338,7 +1338,7 @@ exports[`CreateProject should deal with incorrect platform name if its provided autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -1386,7 +1386,7 @@ exports[`CreateProject should deal with incorrect platform name if its provided valueKey="value" > <div - className="Select css-xabluc-StyledSelect eho28m20 is-searchable Select--single" + className="Select css-dj2cmi-StyledSelect eho28m20 is-searchable Select--single" > <div className="Select-control" @@ -2283,7 +2283,7 @@ exports[`CreateProject should fill in platform name if its provided by url 1`] = <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} height={36} @@ -2297,7 +2297,7 @@ exports[`CreateProject should fill in platform name if its provided by url 1`] = <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} forwardedRef={null} @@ -2314,7 +2314,7 @@ exports[`CreateProject should fill in platform name if its provided by url 1`] = autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -2362,7 +2362,7 @@ exports[`CreateProject should fill in platform name if its provided by url 1`] = valueKey="value" > <div - className="Select css-xabluc-StyledSelect eho28m20 is-searchable Select--single" + className="Select css-dj2cmi-StyledSelect eho28m20 is-searchable Select--single" > <div className="Select-control" @@ -3959,7 +3959,7 @@ exports[`CreateProject should fill in project name if its empty when platform is <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} height={36} @@ -3973,7 +3973,7 @@ exports[`CreateProject should fill in project name if its empty when platform is <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearable={false} deleteRemoves={false} forwardedRef={null} @@ -3990,7 +3990,7 @@ exports[`CreateProject should fill in project name if its empty when platform is autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="css-xabluc-StyledSelect eho28m20" + className="css-dj2cmi-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -4038,7 +4038,7 @@ exports[`CreateProject should fill in project name if its empty when platform is valueKey="value" > <div - className="Select css-xabluc-StyledSelect eho28m20 is-searchable Select--single" + className="Select css-dj2cmi-StyledSelect eho28m20 is-searchable Select--single" > <div className="Select-control" diff --git a/tests/js/spec/components/forms/__snapshots__/selectField.spec.jsx.snap b/tests/js/spec/components/forms/__snapshots__/selectField.spec.jsx.snap index bacae2a0e6092a..01f354d4e32025 100644 --- a/tests/js/spec/components/forms/__snapshots__/selectField.spec.jsx.snap +++ b/tests/js/spec/components/forms/__snapshots__/selectField.spec.jsx.snap @@ -172,7 +172,7 @@ exports[`SelectField renders without form context 1`] = ` <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={true} - className="e1qrhqd00 css-1ua5cd-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-6q5c8d-StyledSelect-StyledSelectControl eho28m20" clearable={true} deleteRemoves={true} disabled={false} @@ -199,7 +199,7 @@ exports[`SelectField renders without form context 1`] = ` <SelectPicker arrowRenderer={[Function]} backspaceRemoves={true} - className="e1qrhqd00 css-1ua5cd-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-6q5c8d-StyledSelect-StyledSelectControl eho28m20" clearable={true} deleteRemoves={true} disabled={false} @@ -229,7 +229,7 @@ exports[`SelectField renders without form context 1`] = ` autosize={true} backspaceRemoves={true} backspaceToRemoveMessage="Press backspace to remove {label}" - className="e1qrhqd00 css-1ua5cd-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-6q5c8d-StyledSelect-StyledSelectControl eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -289,7 +289,7 @@ exports[`SelectField renders without form context 1`] = ` valueKey="value" > <div - className="Select e1qrhqd00 css-1ua5cd-StyledSelect-StyledSelectControl eho28m20 has-value is-clearable is-searchable Select--single" + className="Select e1qrhqd00 css-6q5c8d-StyledSelect-StyledSelectControl eho28m20 has-value is-clearable is-searchable Select--single" > <input disabled={false} diff --git a/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap b/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap index 759927779db19e..5cf11d64efbf82 100644 --- a/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap +++ b/tests/js/spec/views/__snapshots__/ownershipInput.spec.jsx.snap @@ -242,7 +242,7 @@ exports[`Project Ownership Input renders 1`] = ` <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -269,7 +269,7 @@ exports[`Project Ownership Input renders 1`] = ` <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -299,7 +299,7 @@ exports[`Project Ownership Input renders 1`] = ` autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -359,7 +359,7 @@ exports[`Project Ownership Input renders 1`] = ` valueKey="value" > <div - className="Select e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" + className="Select e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" > <input disabled={false} @@ -632,7 +632,7 @@ exports[`Project Ownership Input renders 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -652,7 +652,7 @@ exports[`Project Ownership Input renders 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -673,7 +673,7 @@ exports[`Project Ownership Input renders 1`] = ` autoload={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -700,7 +700,7 @@ exports[`Project Ownership Input renders 1`] = ` backspaceRemoves={true} backspaceToRemoveMessage="Press backspace to remove {label}" cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -752,7 +752,7 @@ exports[`Project Ownership Input renders 1`] = ` valueKey="value" > <div - className="Select css-1dke465-StyledSelect eho28m20 is-clearable is-loading is-searchable Select--multi" + className="Select css-1qogr7d-StyledSelect eho28m20 is-clearable is-loading is-searchable Select--multi" > <div className="Select-control" diff --git a/tests/js/spec/views/__snapshots__/ruleBuilder.spec.jsx.snap b/tests/js/spec/views/__snapshots__/ruleBuilder.spec.jsx.snap index 63bf251bf29134..268753d9adeb97 100644 --- a/tests/js/spec/views/__snapshots__/ruleBuilder.spec.jsx.snap +++ b/tests/js/spec/views/__snapshots__/ruleBuilder.spec.jsx.snap @@ -215,7 +215,7 @@ exports[`RuleBuilder renders 1`] = ` <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -242,7 +242,7 @@ exports[`RuleBuilder renders 1`] = ` <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -272,7 +272,7 @@ exports[`RuleBuilder renders 1`] = ` autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -332,7 +332,7 @@ exports[`RuleBuilder renders 1`] = ` valueKey="value" > <div - className="Select e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" + className="Select e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" > <input disabled={false} @@ -613,7 +613,7 @@ exports[`RuleBuilder renders 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -633,7 +633,7 @@ exports[`RuleBuilder renders 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -654,7 +654,7 @@ exports[`RuleBuilder renders 1`] = ` autoload={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -681,7 +681,7 @@ exports[`RuleBuilder renders 1`] = ` backspaceRemoves={true} backspaceToRemoveMessage="Press backspace to remove {label}" cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -871,7 +871,7 @@ exports[`RuleBuilder renders 1`] = ` valueKey="value" > <div - className="Select css-1dke465-StyledSelect eho28m20 is-clearable is-searchable Select--multi" + className="Select css-1qogr7d-StyledSelect eho28m20 is-clearable is-searchable Select--multi" > <div className="Select-control" @@ -1470,7 +1470,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` <ForwardRef(SelectPicker) arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -1497,7 +1497,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` <SelectPicker arrowRenderer={[Function]} backspaceRemoves={false} - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearable={false} deleteRemoves={false} disabled={false} @@ -1527,7 +1527,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` autosize={true} backspaceRemoves={false} backspaceToRemoveMessage="Press backspace to remove {label}" - className="e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20" + className="e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -1587,7 +1587,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` valueKey="value" > <div - className="Select e1qrhqd00 css-1nab9yw-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" + className="Select e1qrhqd00 css-1j7c7e2-StyledSelect-StyledSelectControl eho28m20 has-value is-searchable Select--single" > <input disabled={false} @@ -2020,7 +2020,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -2078,7 +2078,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` async={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -2137,7 +2137,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` autoload={true} backspaceRemoves={true} cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearable={true} defaultOptions={true} deleteRemoves={true} @@ -2202,7 +2202,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` backspaceRemoves={true} backspaceToRemoveMessage="Press backspace to remove {label}" cache={false} - className="css-1dke465-StyledSelect eho28m20" + className="css-1qogr7d-StyledSelect eho28m20" clearAllText="Clear all" clearRenderer={[Function]} clearValueText="Clear value" @@ -2430,7 +2430,7 @@ exports[`RuleBuilder renders with suggestions 1`] = ` valueKey="value" > <div - className="Select css-1dke465-StyledSelect eho28m20 has-value is-clearable is-focused is-searchable Select--multi" + className="Select css-1qogr7d-StyledSelect eho28m20 has-value is-clearable is-focused is-searchable Select--multi" > <div className="Select-control"
4f159fafe2509e480d002f0dcc4f900b95c30010
2023-09-27 01:06:06
Cathy Teng
fix(github-growth): temp disable hitting missing members api (#56952)
false
temp disable hitting missing members api (#56952)
fix
diff --git a/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx b/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx index bcdeb8ebc3680d..efb833a7220d6d 100644 --- a/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx +++ b/static/app/views/settings/organizationMembers/organizationMembersList.spec.tsx @@ -42,12 +42,12 @@ const roles = [ }, ]; -const missingMembers = [ - { - integration: 'github', - users: TestStubs.MissingMembers(), - }, -]; +// const missingMembers = [ +// { +// integration: 'github', +// users: TestStubs.MissingMembers(), +// }, +// ]; describe('OrganizationMembersList', function () { const members = TestStubs.Members(); @@ -587,52 +587,54 @@ describe('OrganizationMembersList', function () { }); }); - describe('inviteBanner', function () { - it('invites member from banner', async function () { - MockApiClient.addMockResponse({ - url: '/organizations/org-slug/missing-members/', - method: 'GET', - body: missingMembers, - }); - - const newMember = TestStubs.Member({ - id: '6', - email: '[email protected]', - teams: [], - teamRoles: [], - flags: { - 'sso:linked': true, - 'idp:provisioned': false, - }, - }); - - MockApiClient.addMockResponse({ - url: '/organizations/org-slug/members/?referrer=github_nudge_invite', - method: 'POST', - body: newMember, - }); - - const org = TestStubs.Organization({ - features: ['integrations-gh-invite'], - githubNudgeInvite: true, - }); - - render(<OrganizationMembersList {...defaultProps} organization={org} />, { - context: TestStubs.routerContext([{organization: org}]), - }); - - expect( - await screen.findByRole('heading', { - name: 'Bring your full GitHub team on board in Sentry', - }) - ).toBeInTheDocument(); - expect(screen.queryAllByTestId('invite-missing-member')).toHaveLength(5); - expect(screen.getByText('See all 5 missing members')).toBeInTheDocument(); - - const inviteButton = screen.queryAllByTestId('invite-missing-member')[0]; - await userEvent.click(inviteButton); - expect(screen.queryAllByTestId('invite-missing-member')).toHaveLength(4); - expect(screen.getByText('See all 4 missing members')).toBeInTheDocument(); - }); - }); + // TODO(cathy): uncomment + + // describe('inviteBanner', function () { + // it('invites member from banner', async function () { + // MockApiClient.addMockResponse({ + // url: '/organizations/org-slug/missing-members/', + // method: 'GET', + // body: missingMembers, + // }); + + // const newMember = TestStubs.Member({ + // id: '6', + // email: '[email protected]', + // teams: [], + // teamRoles: [], + // flags: { + // 'sso:linked': true, + // 'idp:provisioned': false, + // }, + // }); + + // MockApiClient.addMockResponse({ + // url: '/organizations/org-slug/members/?referrer=github_nudge_invite', + // method: 'POST', + // body: newMember, + // }); + + // const org = TestStubs.Organization({ + // features: ['integrations-gh-invite'], + // githubNudgeInvite: true, + // }); + + // render(<OrganizationMembersList {...defaultProps} organization={org} />, { + // context: TestStubs.routerContext([{organization: org}]), + // }); + + // expect( + // await screen.findByRole('heading', { + // name: 'Bring your full GitHub team on board in Sentry', + // }) + // ).toBeInTheDocument(); + // expect(screen.queryAllByTestId('invite-missing-member')).toHaveLength(5); + // expect(screen.getByText('See all 5 missing members')).toBeInTheDocument(); + + // const inviteButton = screen.queryAllByTestId('invite-missing-member')[0]; + // await userEvent.click(inviteButton); + // expect(screen.queryAllByTestId('invite-missing-member')).toHaveLength(4); + // expect(screen.getByText('See all 4 missing members')).toBeInTheDocument(); + // }); + // }); }); diff --git a/static/app/views/settings/organizationMembers/organizationMembersList.tsx b/static/app/views/settings/organizationMembers/organizationMembersList.tsx index ab784df1ee397e..00896a091870d1 100644 --- a/static/app/views/settings/organizationMembers/organizationMembersList.tsx +++ b/static/app/views/settings/organizationMembers/organizationMembersList.tsx @@ -96,12 +96,12 @@ class OrganizationMembersList extends DeprecatedAsyncView<Props, State> { ], ['inviteRequests', `/organizations/${organization.slug}/invite-requests/`], - [ - 'missingMembers', - `/organizations/${organization.slug}/missing-members/`, - {}, - {allowError: error => error.status === 403}, - ], + // [ + // 'missingMembers', + // `/organizations/${organization.slug}/missing-members/`, + // {}, + // {allowError: error => error.status === 403}, + // ], ]; }
c33d3555e74a92967b558beb25e709316c1925a0
2022-02-11 04:08:46
Taylan Gocmen
fix(alerts): Set default timeWindow to 1h and display to 14d in alert wizard (#31252)
false
Set default timeWindow to 1h and display to 14d in alert wizard (#31252)
fix
diff --git a/static/app/views/alerts/incidentRules/constants.tsx b/static/app/views/alerts/incidentRules/constants.tsx index 3889cd0e953f65..54dba4ef6450e1 100644 --- a/static/app/views/alerts/incidentRules/constants.tsx +++ b/static/app/views/alerts/incidentRules/constants.tsx @@ -130,7 +130,7 @@ export function createDefaultRule( eventTypes: [EventTypes.ERROR], aggregate: DEFAULT_AGGREGATE, query: '', - timeWindow: 1, + timeWindow: 60, thresholdPeriod: 1, triggers: [createDefaultTrigger('critical'), createDefaultTrigger('warning')], projects: [], diff --git a/tests/js/spec/views/alerts/incidentRules/create.spec.jsx b/tests/js/spec/views/alerts/incidentRules/create.spec.jsx index 6cc8d93adccffb..0f0afc62b992a7 100644 --- a/tests/js/spec/views/alerts/incidentRules/create.spec.jsx +++ b/tests/js/spec/views/alerts/incidentRules/create.spec.jsx @@ -53,10 +53,10 @@ describe('Incident Rules Create', function () { expect.anything(), expect.objectContaining({ query: { - interval: '1m', + interval: '60m', project: [2], query: 'event.type:error', - statsPeriod: '1d', + statsPeriod: '14d', yAxis: 'count()', referrer: 'api.organization-event-stats', },
eef2e2c40fbb731480476cf91192b9aa33412fc7
2024-07-01 23:22:49
anthony sottile
ref: fix accessing user_id from Member in tests (#73587)
false
fix accessing user_id from Member in tests (#73587)
ref
diff --git a/tests/sentry/runner/commands/test_createuser.py b/tests/sentry/runner/commands/test_createuser.py index ac83b23eaac66e..89d47bebfca72e 100644 --- a/tests/sentry/runner/commands/test_createuser.py +++ b/tests/sentry/runner/commands/test_createuser.py @@ -66,6 +66,7 @@ def test_single_org(self): with assume_test_silo_mode(SiloMode.REGION): assert OrganizationMember.objects.count() == 1 member = OrganizationMember.objects.all()[0] + assert member.user_id is not None u = user_service.get_user(user_id=member.user_id) assert u assert u.email == "[email protected]" @@ -80,6 +81,7 @@ def test_single_org_superuser(self): with assume_test_silo_mode(SiloMode.REGION): assert OrganizationMember.objects.count() == 1 member = OrganizationMember.objects.all()[0] + assert member.user_id is not None u = user_service.get_user(user_id=member.user_id) assert u assert u.email == "[email protected]"
ec8b9373675be96888f3d20fbbb697ac8352073f
2023-02-16 21:04:11
anthony sottile
ref: make Authenticator config compatible with write_json=True (#44606)
false
make Authenticator config compatible with write_json=True (#44606)
ref
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt index 6ef095f51296f9..cf2d887835196d 100644 --- a/migrations_lockfile.txt +++ b/migrations_lockfile.txt @@ -6,5 +6,5 @@ To resolve this, rebase against latest master and regenerate your migration. Thi will then be regenerated, and you should be able to merge without conflicts. nodestore: 0002_nodestore_no_dictfield -sentry: 0359_checkin_file_field +sentry: 0360_authenticator_config_type_change social_auth: 0001_initial diff --git a/src/sentry/migrations/0360_authenticator_config_type_change.py b/src/sentry/migrations/0360_authenticator_config_type_change.py new file mode 100644 index 00000000000000..970565e8f5bea3 --- /dev/null +++ b/src/sentry/migrations/0360_authenticator_config_type_change.py @@ -0,0 +1,32 @@ +# Generated by Django 2.2.28 on 2023-02-16 15:14 + +from django.db import migrations + +import sentry.models.authenticator +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", "0359_checkin_file_field"), + ] + + operations = [ + migrations.AlterField( + model_name="authenticator", + name="config", + field=sentry.models.authenticator.AuthenticatorConfig(editable=False), + ), + ] diff --git a/src/sentry/models/authenticator.py b/src/sentry/models/authenticator.py index 9bd7791c239376..aacd6d3fd439bd 100644 --- a/src/sentry/models/authenticator.py +++ b/src/sentry/models/authenticator.py @@ -1,7 +1,14 @@ +from __future__ import annotations + +import base64 +import copy +from typing import Any + from django.db import models from django.utils import timezone from django.utils.functional import cached_property from django.utils.translation import ugettext_lazy as _ +from fido2.ctap2 import AuthenticatorData from sentry.auth.authenticators import ( AUTHENTICATOR_CHOICES, @@ -112,6 +119,35 @@ def bulk_users_have_2fa(self, user_ids): return {id: id in authenticators for id in user_ids} +class AuthenticatorConfig(PickledObjectField): + def __init__(self, *args, **kwargs): + # we have special logic to handle pickle compat + kwargs.setdefault("disable_pickle_validation", True) + super().__init__(*args, **kwargs) + + def _is_devices_config(self, value: Any) -> bool: + return isinstance(value, dict) and "devices" in value + + def get_db_prep_value(self, value, *args, **kwargs): + if self.write_json and self._is_devices_config(value): + # avoid mutating the original object + value = copy.deepcopy(value) + for device in value["devices"]: + # AuthenticatorData is a non-json-serializable bytes subclass + if isinstance(device["binding"], AuthenticatorData): + device["binding"] = base64.b64encode(device["binding"]).decode() + + return super().get_db_prep_value(value, *args, **kwargs) + + def to_python(self, value): + ret = super().to_python(value) + if self._is_devices_config(ret): + for device in ret["devices"]: + if isinstance(device["binding"], str): + device["binding"] = AuthenticatorData(base64.b64decode(device["binding"])) + return ret + + @control_silo_only_model class Authenticator(BaseModel): __include_in_export__ = True @@ -122,11 +158,7 @@ class Authenticator(BaseModel): last_used_at = models.DateTimeField(_("last used at"), null=True) type = BoundedPositiveIntegerField(choices=AUTHENTICATOR_CHOICES) - # This field stores bytes and as such cannot currently - # be serialized by our JSON serializer. This would require - # further changes. As such this validation is currently - # disabled to make tests pass. - config = PickledObjectField(disable_pickle_validation=True) + config = AuthenticatorConfig() objects = AuthenticatorManager() diff --git a/tests/sentry/api/endpoints/test_user_authenticator_details.py b/tests/sentry/api/endpoints/test_user_authenticator_details.py index 7cfda232b63b79..d0454ca8077720 100644 --- a/tests/sentry/api/endpoints/test_user_authenticator_details.py +++ b/tests/sentry/api/endpoints/test_user_authenticator_details.py @@ -1,6 +1,7 @@ import datetime from unittest import mock +import pytest from django.conf import settings from django.core import mail from django.db.models import F @@ -186,6 +187,18 @@ def test_rename_device_not_found(self): ) [email protected] +def pickle_mode_alternate(): + field = Authenticator._meta.get_field("config") + with mock.patch.object(field, "write_json", not field.write_json): + yield + + [email protected]("pickle_mode_alternate") +class PickleModeUserAuthenticatorDeviceDetailsTest(UserAuthenticatorDeviceDetailsTest): + pass + + @control_silo_test class UserAuthenticatorDetailsTest(UserAuthenticatorDetailsTestBase): endpoint = "sentry-api-0-user-authenticator-details" diff --git a/tests/sentry/models/test_authenticator.py b/tests/sentry/models/test_authenticator.py index cd5617ff5ff704..7d02d5c7d775fe 100644 --- a/tests/sentry/models/test_authenticator.py +++ b/tests/sentry/models/test_authenticator.py @@ -1,5 +1,9 @@ +from fido2.ctap2 import AuthenticatorData +from fido2.utils import sha256 + from sentry.auth.authenticators import RecoveryCodeInterface, TotpInterface -from sentry.models import Authenticator +from sentry.auth.authenticators.u2f import create_credential_object +from sentry.models.authenticator import Authenticator, AuthenticatorConfig from sentry.testutils import TestCase from sentry.testutils.silo import control_silo_test @@ -32,3 +36,44 @@ def test_bulk_users_have_2fa(self): user2.id: False, 9999: False, } + + +def test_authenticator_config_compatibility(): + field_pickle = AuthenticatorConfig(write_json=False) + field_json = AuthenticatorConfig(write_json=True) + + value = { + "devices": [ + { + "binding": { + "publicKey": "publickey", + "keyHandle": "aowerkoweraowerkkro", + "appId": "https://dev.getsentry.net:8000/auth/2fa/u2fappid.json", + }, + "name": "Sentry", + "ts": 1512505334, + }, + { + "name": "Alert Escargot", + "ts": 1512505334, + "binding": AuthenticatorData.create( + sha256(b"test"), + 0x41, + 1, + create_credential_object( + { + "publicKey": "webauthn", + "keyHandle": "webauthn", + } + ), + ), + }, + ] + } + + enc_pickle = field_pickle.get_db_prep_value(value) + enc_json = field_json.get_db_prep_value(value) + + for field in (field_pickle, field_json): + for enc in (enc_pickle, enc_json): + assert value == field.to_python(enc)
a2a27217b69fd195047b20f5530d5d1f56df856f
2022-01-07 00:41:29
Scott Cooper
feat(alerts): Add filtering issue alert rules by `sdk.name` (#30922)
false
Add filtering issue alert rules by `sdk.name` (#30922)
feat
diff --git a/src/sentry/rules/conditions/event_attribute.py b/src/sentry/rules/conditions/event_attribute.py index eefce3086aa4e7..21c77e00b88d73 100644 --- a/src/sentry/rules/conditions/event_attribute.py +++ b/src/sentry/rules/conditions/event_attribute.py @@ -46,6 +46,7 @@ class MatchType: "user.ip_address", "http.method", "http.url", + "sdk.name", "stacktrace.code", "stacktrace.module", "stacktrace.filename", @@ -145,6 +146,11 @@ def _get_attribute_values(self, event, attr): return [getattr(event.interfaces["request"], path[1])] + elif path[0] == "sdk": + if path[1] != "name": + return [] + return [event.data["sdk"].get(path[1])] + elif path[0] == "stacktrace": stacks = event.interfaces.get("stacktrace") if stacks: diff --git a/tests/sentry/rules/conditions/test_event_attribute.py b/tests/sentry/rules/conditions/test_event_attribute.py index 5b78f46585d7b2..e29304a7c83706 100644 --- a/tests/sentry/rules/conditions/test_event_attribute.py +++ b/tests/sentry/rules/conditions/test_event_attribute.py @@ -36,6 +36,7 @@ def get_event(self, **kwargs): "tags": [("environment", "production")], "extra": {"foo": {"bar": "baz"}, "biz": ["baz"], "bar": "foo"}, "platform": "php", + "sdk": {"name": "sentry.javascript.react", "version": "6.16.1"}, } data.update(kwargs) event = self.store_event(data, project_id=self.project.id) @@ -298,6 +299,22 @@ def test_exception_value(self): ) self.assertDoesNotPass(rule, event) + def test_sdk_name(self): + event = self.get_event() + rule = self.get_rule( + data={ + "match": MatchType.EQUAL, + "attribute": "sdk.name", + "value": "sentry.javascript.react", + } + ) + self.assertPasses(rule, event) + + rule = self.get_rule( + data={"match": MatchType.EQUAL, "attribute": "sdk.name", "value": "sentry.python"} + ) + self.assertDoesNotPass(rule, event) + def test_stacktrace_filename(self): """Stacktrace.filename should match frames anywhere in the stack."""
a43f716a9bef038dcdea8b315074c87774e36a67
2024-04-22 22:03:10
Yagiz Nizipli
perf: reduce barrel file usages (#69421)
false
reduce barrel file usages (#69421)
perf
diff --git a/static/app/components/badge/groupPriority.stories.tsx b/static/app/components/badge/groupPriority.stories.tsx index 73b456d3f58a16..9b58ce944d3c0e 100644 --- a/static/app/components/badge/groupPriority.stories.tsx +++ b/static/app/components/badge/groupPriority.stories.tsx @@ -6,7 +6,7 @@ import { } from 'sentry/components/badge/groupPriority'; import SideBySide from 'sentry/components/stories/sideBySide'; import storyBook from 'sentry/stories/storyBook'; -import {PriorityLevel} from 'sentry/types'; +import {PriorityLevel} from 'sentry/types/group'; const PRIORITIES = [PriorityLevel.HIGH, PriorityLevel.MEDIUM, PriorityLevel.LOW]; diff --git a/static/app/components/charts/chartZoom.tsx b/static/app/components/charts/chartZoom.tsx index e3dc99f26a5c37..93c8c8fd50f41a 100644 --- a/static/app/components/charts/chartZoom.tsx +++ b/static/app/components/charts/chartZoom.tsx @@ -13,7 +13,7 @@ import {updateDateTime} from 'sentry/actionCreators/pageFilters'; import DataZoomInside from 'sentry/components/charts/components/dataZoomInside'; import DataZoomSlider from 'sentry/components/charts/components/dataZoomSlider'; import ToolBox from 'sentry/components/charts/components/toolBox'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type { EChartChartReadyHandler, EChartDataZoomHandler, diff --git a/static/app/components/comboBox/types.tsx b/static/app/components/comboBox/types.tsx index daab8f854d57fa..5bb34994456b2c 100644 --- a/static/app/components/comboBox/types.tsx +++ b/static/app/components/comboBox/types.tsx @@ -1,4 +1,4 @@ -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; export type SelectKey = string | number; diff --git a/static/app/components/commitLink.tsx b/static/app/components/commitLink.tsx index ec2960101cc7ad..3d894b276491e6 100644 --- a/static/app/components/commitLink.tsx +++ b/static/app/components/commitLink.tsx @@ -3,7 +3,7 @@ import ExternalLink from 'sentry/components/links/externalLink'; import {IconBitbucket, IconGithub, IconGitlab, IconVsts} from 'sentry/icons'; import type {SVGIconProps} from 'sentry/icons/svgIcon'; import {t} from 'sentry/locale'; -import type {Repository} from 'sentry/types'; +import type {Repository} from 'sentry/types/integrations'; import {getShortCommitHash} from 'sentry/utils'; type CommitFormatterParameters = { diff --git a/static/app/components/commitRow.spec.tsx b/static/app/components/commitRow.spec.tsx index f58c7b0429d043..e9f642e28b54f7 100644 --- a/static/app/components/commitRow.spec.tsx +++ b/static/app/components/commitRow.spec.tsx @@ -5,8 +5,9 @@ import {textWithMarkupMatcher} from 'sentry-test/utils'; import {openInviteMembersModal} from 'sentry/actionCreators/modal'; import {CommitRow} from 'sentry/components/commitRow'; -import type {Commit, Repository, User} from 'sentry/types'; -import {RepositoryStatus} from 'sentry/types'; +import type {Commit, Repository} from 'sentry/types/integrations'; +import {RepositoryStatus} from 'sentry/types/integrations'; +import type {User} from 'sentry/types/user'; jest.mock('sentry/components/hovercard', () => { return { diff --git a/static/app/components/commitRow.tsx b/static/app/components/commitRow.tsx index 6c5679e7b0745b..dbdbfb8b2dd081 100644 --- a/static/app/components/commitRow.tsx +++ b/static/app/components/commitRow.tsx @@ -15,7 +15,7 @@ import {IconWarning} from 'sentry/icons'; import {t, tct} from 'sentry/locale'; import ConfigStore from 'sentry/stores/configStore'; import {space} from 'sentry/styles/space'; -import type {Commit} from 'sentry/types'; +import type {Commit} from 'sentry/types/integrations'; export function formatCommitMessage(message: string | null) { if (!message) { diff --git a/static/app/components/compactSelect/types.tsx b/static/app/components/compactSelect/types.tsx index dce50042bf9524..67cc064860e16f 100644 --- a/static/app/components/compactSelect/types.tsx +++ b/static/app/components/compactSelect/types.tsx @@ -1,4 +1,4 @@ -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; export type SelectKey = string | number; diff --git a/static/app/components/contextPickerModal.tsx b/static/app/components/contextPickerModal.tsx index 5bacdea5a52fe0..3900c3690b10ae 100644 --- a/static/app/components/contextPickerModal.tsx +++ b/static/app/components/contextPickerModal.tsx @@ -15,7 +15,9 @@ import ConfigStore from 'sentry/stores/configStore'; import OrganizationsStore from 'sentry/stores/organizationsStore'; import OrganizationStore from 'sentry/stores/organizationStore'; import {space} from 'sentry/styles/space'; -import type {Integration, Organization, Project} from 'sentry/types'; +import type {Integration} from 'sentry/types/integrations'; +import type {Organization} from 'sentry/types/organization'; +import type {Project} from 'sentry/types/project'; import Projects from 'sentry/utils/projects'; import replaceRouterParams from 'sentry/utils/replaceRouterParams'; import IntegrationIcon from 'sentry/views/settings/organizationIntegrations/integrationIcon'; diff --git a/static/app/components/customCommitsResolutionModal.tsx b/static/app/components/customCommitsResolutionModal.tsx index b0d21f8d8ac69e..a29e106577603c 100644 --- a/static/app/components/customCommitsResolutionModal.tsx +++ b/static/app/components/customCommitsResolutionModal.tsx @@ -7,7 +7,8 @@ import TimeSince from 'sentry/components/timeSince'; import Version from 'sentry/components/version'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Commit, ResolvedStatusDetails} from 'sentry/types'; +import type {ResolvedStatusDetails} from 'sentry/types/group'; +import type {Commit} from 'sentry/types/integrations'; interface CustomCommitsResolutionModalProps extends ModalRenderProps { onSelected: (x: ResolvedStatusDetails) => void; diff --git a/static/app/components/customIgnoreCountModal.tsx b/static/app/components/customIgnoreCountModal.tsx index ebd0ef39cb86cb..51b817f47fed4b 100644 --- a/static/app/components/customIgnoreCountModal.tsx +++ b/static/app/components/customIgnoreCountModal.tsx @@ -6,7 +6,8 @@ import ButtonBar from 'sentry/components/buttonBar'; import NumberField from 'sentry/components/forms/fields/numberField'; import SelectField from 'sentry/components/forms/fields/selectField'; import {t} from 'sentry/locale'; -import type {IgnoredStatusDetails, SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; +import type {IgnoredStatusDetails} from 'sentry/types/group'; type CountNames = 'ignoreCount' | 'ignoreUserCount'; type WindowNames = 'ignoreWindow' | 'ignoreUserWindow'; diff --git a/static/app/components/customResolutionModal.tsx b/static/app/components/customResolutionModal.tsx index f866af7a3073bb..d3e821fc223ac2 100644 --- a/static/app/components/customResolutionModal.tsx +++ b/static/app/components/customResolutionModal.tsx @@ -8,7 +8,8 @@ import Version from 'sentry/components/version'; import {t} from 'sentry/locale'; import configStore from 'sentry/stores/configStore'; import {space} from 'sentry/styles/space'; -import type {Organization, Release} from 'sentry/types'; +import type {Organization} from 'sentry/types/organization'; +import type {Release} from 'sentry/types/release'; import {isVersionInfoSemver} from 'sentry/views/releases/utils'; interface CustomResolutionModalProps extends ModalRenderProps { diff --git a/static/app/components/demoSandboxButton.tsx b/static/app/components/demoSandboxButton.tsx index ca9918d9c0269f..ff8aa0082349df 100644 --- a/static/app/components/demoSandboxButton.tsx +++ b/static/app/components/demoSandboxButton.tsx @@ -1,6 +1,7 @@ import type {ButtonProps} from 'sentry/components/button'; import {Button} from 'sentry/components/button'; -import type {Organization, SandboxData} from 'sentry/types'; +import type {Organization} from 'sentry/types/organization'; +import type {SandboxData} from 'sentry/types/sandbox'; import {trackAnalytics} from 'sentry/utils/analytics'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/deprecatedforms/selectCreatableField.tsx b/static/app/components/deprecatedforms/selectCreatableField.tsx index bc4119a5191e69..9fff96da486f41 100644 --- a/static/app/components/deprecatedforms/selectCreatableField.tsx +++ b/static/app/components/deprecatedforms/selectCreatableField.tsx @@ -3,7 +3,7 @@ import styled from '@emotion/styled'; import {StyledForm} from 'sentry/components/deprecatedforms/form'; import SelectField from 'sentry/components/deprecatedforms/selectField'; import SelectControl from 'sentry/components/forms/controls/selectControl'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {defined} from 'sentry/utils'; import convertFromSelect2Choices from 'sentry/utils/convertFromSelect2Choices'; diff --git a/static/app/components/discover/quickContextCommitRow.spec.tsx b/static/app/components/discover/quickContextCommitRow.spec.tsx index 4164bccf78152f..2076bef5e3090a 100644 --- a/static/app/components/discover/quickContextCommitRow.spec.tsx +++ b/static/app/components/discover/quickContextCommitRow.spec.tsx @@ -1,7 +1,7 @@ import {render, screen} from 'sentry-test/reactTestingLibrary'; import type {Commit, Repository, User} from 'sentry/types'; -import {RepositoryStatus} from 'sentry/types'; +import {RepositoryStatus} from 'sentry/types/integrations'; import {QuickContextCommitRow} from './quickContextCommitRow'; diff --git a/static/app/components/eventOrGroupHeader.spec.tsx b/static/app/components/eventOrGroupHeader.spec.tsx index 53770750891aec..db64ab2e057dfb 100644 --- a/static/app/components/eventOrGroupHeader.spec.tsx +++ b/static/app/components/eventOrGroupHeader.spec.tsx @@ -7,7 +7,7 @@ import {render, screen} from 'sentry-test/reactTestingLibrary'; import {textWithMarkupMatcher} from 'sentry-test/utils'; import EventOrGroupHeader from 'sentry/components/eventOrGroupHeader'; -import {EventOrGroupType} from 'sentry/types'; +import {EventOrGroupType} from 'sentry/types/event'; const group = GroupFixture({ level: 'error', diff --git a/static/app/components/eventOrGroupTitle.spec.tsx b/static/app/components/eventOrGroupTitle.spec.tsx index bbca1a90d2bf44..41c742575d3be8 100644 --- a/static/app/components/eventOrGroupTitle.spec.tsx +++ b/static/app/components/eventOrGroupTitle.spec.tsx @@ -5,8 +5,9 @@ import {UserFixture} from 'sentry-fixture/user'; import {render, screen} from 'sentry-test/reactTestingLibrary'; import EventOrGroupTitle from 'sentry/components/eventOrGroupTitle'; -import type {BaseGroup} from 'sentry/types'; -import {EventOrGroupType, IssueCategory} from 'sentry/types'; +import {EventOrGroupType} from 'sentry/types/event'; +import type {BaseGroup} from 'sentry/types/group'; +import {IssueCategory} from 'sentry/types/group'; describe('EventOrGroupTitle', function () { const data = { diff --git a/static/app/components/events/attachmentViewers/utils.tsx b/static/app/components/events/attachmentViewers/utils.tsx index cc57dc7cbe4ed4..62c9f690fde946 100644 --- a/static/app/components/events/attachmentViewers/utils.tsx +++ b/static/app/components/events/attachmentViewers/utils.tsx @@ -1,5 +1,5 @@ -import type {EventAttachment} from 'sentry/types'; import type {Event} from 'sentry/types/event'; +import type {EventAttachment} from 'sentry/types/group'; export type ViewerProps = { attachment: EventAttachment; diff --git a/static/app/components/events/autofix/index.tsx b/static/app/components/events/autofix/index.tsx index ec7f0efae4d7b2..0c8fe782a1d7c1 100644 --- a/static/app/components/events/autofix/index.tsx +++ b/static/app/components/events/autofix/index.tsx @@ -4,7 +4,7 @@ import {AutofixCard} from 'sentry/components/events/autofix/autofixCard'; import type {GroupWithAutofix} from 'sentry/components/events/autofix/types'; import {useAiAutofix} from 'sentry/components/events/autofix/useAutofix'; import {useAutofixSetup} from 'sentry/components/events/autofix/useAutofixSetup'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; interface Props { event: Event; diff --git a/static/app/components/events/autofix/types.ts b/static/app/components/events/autofix/types.ts index 89db3820e6c63b..9a853e4bf92912 100644 --- a/static/app/components/events/autofix/types.ts +++ b/static/app/components/events/autofix/types.ts @@ -1,4 +1,5 @@ -import type {EventMetadata, Group} from 'sentry/types'; +import type {EventMetadata} from 'sentry/types/event'; +import type {Group} from 'sentry/types/group'; export enum DiffFileType { ADDED = 'A', diff --git a/static/app/components/events/autofix/useAutofix.tsx b/static/app/components/events/autofix/useAutofix.tsx index 5ffd4a668823ff..59531c73c06b83 100644 --- a/static/app/components/events/autofix/useAutofix.tsx +++ b/static/app/components/events/autofix/useAutofix.tsx @@ -5,7 +5,7 @@ import { AutofixStepType, type GroupWithAutofix, } from 'sentry/components/events/autofix/types'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import { type ApiQueryKey, setApiQueryData, diff --git a/static/app/components/events/contextSummary/types.tsx b/static/app/components/events/contextSummary/types.tsx index e84de6e5c6b652..16b1f0db85846a 100644 --- a/static/app/components/events/contextSummary/types.tsx +++ b/static/app/components/events/contextSummary/types.tsx @@ -1,4 +1,4 @@ -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; type Meta = NonNullable<Event['_meta']>; diff --git a/static/app/components/events/contexts/browser/index.tsx b/static/app/components/events/contexts/browser/index.tsx index 6db7980b4c0d57..0a51209fd8e159 100644 --- a/static/app/components/events/contexts/browser/index.tsx +++ b/static/app/components/events/contexts/browser/index.tsx @@ -1,7 +1,7 @@ import {Fragment} from 'react'; import ContextBlock from 'sentry/components/events/contexts/contextBlock'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import { getContextMeta, diff --git a/static/app/components/events/contexts/contextBlock.tsx b/static/app/components/events/contexts/contextBlock.tsx index b19dafb522f89c..767f97f06ebe9f 100644 --- a/static/app/components/events/contexts/contextBlock.tsx +++ b/static/app/components/events/contexts/contextBlock.tsx @@ -1,6 +1,6 @@ import ErrorBoundary from 'sentry/components/errorBoundary'; import KeyValueList from 'sentry/components/events/interfaces/keyValueList'; -import type {KeyValueListData} from 'sentry/types'; +import type {KeyValueListData} from 'sentry/types/group'; type Props = { data: KeyValueListData; diff --git a/static/app/components/events/contexts/contextCard.tsx b/static/app/components/events/contexts/contextCard.tsx index 64736552915128..4fcb52830f6a82 100644 --- a/static/app/components/events/contexts/contextCard.tsx +++ b/static/app/components/events/contexts/contextCard.tsx @@ -10,8 +10,9 @@ import {AnnotatedTextErrors} from 'sentry/components/events/meta/annotatedText/a import Panel from 'sentry/components/panels/panel'; import {StructuredData} from 'sentry/components/structuredEventData'; import {space} from 'sentry/styles/space'; -import type {Group, Project} from 'sentry/types'; import type {Event} from 'sentry/types/event'; +import type {Group} from 'sentry/types/group'; +import type {Project} from 'sentry/types/project'; import {defined, objectIsEmpty} from 'sentry/utils'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/events/contexts/operatingSystem/index.tsx b/static/app/components/events/contexts/operatingSystem/index.tsx index 9caef5ff08dfdc..ec1f0c941b26eb 100644 --- a/static/app/components/events/contexts/operatingSystem/index.tsx +++ b/static/app/components/events/contexts/operatingSystem/index.tsx @@ -1,7 +1,7 @@ import {Fragment} from 'react'; import ContextBlock from 'sentry/components/events/contexts/contextBlock'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import { getContextMeta, diff --git a/static/app/components/events/eventStatisticalDetector/functionBreakpointChart.tsx b/static/app/components/events/eventStatisticalDetector/functionBreakpointChart.tsx index 06a8b3c546a9bf..7f2fc8f7d67901 100644 --- a/static/app/components/events/eventStatisticalDetector/functionBreakpointChart.tsx +++ b/static/app/components/events/eventStatisticalDetector/functionBreakpointChart.tsx @@ -3,7 +3,7 @@ import * as Sentry from '@sentry/react'; import Chart from 'sentry/components/events/eventStatisticalDetector/lineChart'; import {DataSection} from 'sentry/components/events/styles'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {defined} from 'sentry/utils'; import {useProfileEventsStats} from 'sentry/utils/profiling/hooks/useProfileEventsStats'; import {useRelativeDateTime} from 'sentry/utils/profiling/hooks/useRelativeDateTime'; diff --git a/static/app/components/events/eventStatisticalDetector/spanOpBreakdown.tsx b/static/app/components/events/eventStatisticalDetector/spanOpBreakdown.tsx index 8d8fa7fe5dd0bb..84740fc4f985bb 100644 --- a/static/app/components/events/eventStatisticalDetector/spanOpBreakdown.tsx +++ b/static/app/components/events/eventStatisticalDetector/spanOpBreakdown.tsx @@ -10,7 +10,7 @@ import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable' import LoadingIndicator from 'sentry/components/loadingIndicator'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {defined} from 'sentry/utils'; import {useDiscoverQuery} from 'sentry/utils/discover/discoverQuery'; import EventView from 'sentry/utils/discover/eventView'; diff --git a/static/app/components/events/eventTagsAndScreenshot/index.spec.tsx b/static/app/components/events/eventTagsAndScreenshot/index.spec.tsx index b376151aaa3d78..2fa9e9abb5faa1 100644 --- a/static/app/components/events/eventTagsAndScreenshot/index.spec.tsx +++ b/static/app/components/events/eventTagsAndScreenshot/index.spec.tsx @@ -12,12 +12,11 @@ import { within, } from 'sentry-test/reactTestingLibrary'; +import {deviceNameMapper} from 'sentry/components/deviceName'; import {TagFilter} from 'sentry/components/events/eventTags/util'; import {EventTagsAndScreenshot} from 'sentry/components/events/eventTagsAndScreenshot'; import GlobalModal from 'sentry/components/globalModal'; -import type {EventAttachment} from 'sentry/types'; - -import {deviceNameMapper} from '../../../../../static/app/components/deviceName'; +import type {EventAttachment} from 'sentry/types/group'; describe('EventTagsAndScreenshot', function () { const contexts = { diff --git a/static/app/components/events/interfaces/crashContent/exception/sourceMapDebug.tsx b/static/app/components/events/interfaces/crashContent/exception/sourceMapDebug.tsx index 77e0b359836c5f..e2aa685247dccd 100644 --- a/static/app/components/events/interfaces/crashContent/exception/sourceMapDebug.tsx +++ b/static/app/components/events/interfaces/crashContent/exception/sourceMapDebug.tsx @@ -11,7 +11,7 @@ import ListItem from 'sentry/components/list/listItem'; import {IconWarning} from 'sentry/icons'; import {t, tct, tn} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {defined} from 'sentry/utils'; import {trackAnalytics} from 'sentry/utils/analytics'; import {getAnalyticsDataForEvent} from 'sentry/utils/events'; diff --git a/static/app/components/events/interfaces/message.tsx b/static/app/components/events/interfaces/message.tsx index 890b2b57279f12..b6fb8617011bc6 100644 --- a/static/app/components/events/interfaces/message.tsx +++ b/static/app/components/events/interfaces/message.tsx @@ -3,7 +3,7 @@ import {renderLinksInText} from 'sentry/components/events/interfaces/crashConten import KeyValueList from 'sentry/components/events/interfaces/keyValueList'; import {AnnotatedText} from 'sentry/components/events/meta/annotatedText'; import {t} from 'sentry/locale'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {EntryType} from 'sentry/types/event'; import {objectIsEmpty} from 'sentry/utils'; diff --git a/static/app/components/events/interfaces/performance/resources.tsx b/static/app/components/events/interfaces/performance/resources.tsx index 6098fcfc04da30..1e12143b195dfc 100644 --- a/static/app/components/events/interfaces/performance/resources.tsx +++ b/static/app/components/events/interfaces/performance/resources.tsx @@ -3,7 +3,7 @@ import styled from '@emotion/styled'; import ExternalLink from 'sentry/components/links/externalLink'; import {IconDocs} from 'sentry/icons'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {trackAnalytics} from 'sentry/utils/analytics'; import type {IssueTypeConfig} from 'sentry/utils/issueTypeConfig/types'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/events/profileEventEvidence.tsx b/static/app/components/events/profileEventEvidence.tsx index ba3ea93c3d1021..7f2fccefdcc307 100644 --- a/static/app/components/events/profileEventEvidence.tsx +++ b/static/app/components/events/profileEventEvidence.tsx @@ -3,7 +3,7 @@ import {EventDataSection} from 'sentry/components/events/eventDataSection'; import KeyValueList from 'sentry/components/events/interfaces/keyValueList'; import {IconProfiling} from 'sentry/icons'; import {t} from 'sentry/locale'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls'; import {generateProfileFlamechartRouteWithHighlightFrame} from 'sentry/utils/profiling/routes'; import {useLocation} from 'sentry/utils/useLocation'; diff --git a/static/app/components/feedback/feedbackItem/feedbackActions.tsx b/static/app/components/feedback/feedbackItem/feedbackActions.tsx index 3ac0c3782d545a..526c3cc96c02a7 100644 --- a/static/app/components/feedback/feedbackItem/feedbackActions.tsx +++ b/static/app/components/feedback/feedbackItem/feedbackActions.tsx @@ -10,7 +10,7 @@ import {Flex} from 'sentry/components/profiling/flex'; import {IconEllipsis} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {defined} from 'sentry/utils'; import type {FeedbackIssue} from 'sentry/utils/feedback/types'; diff --git a/static/app/components/feedback/feedbackItem/feedbackItem.tsx b/static/app/components/feedback/feedbackItem/feedbackItem.tsx index 0982738c6fcf4e..84ecf80e326f14 100644 --- a/static/app/components/feedback/feedbackItem/feedbackItem.tsx +++ b/static/app/components/feedback/feedbackItem/feedbackItem.tsx @@ -15,7 +15,7 @@ import TextCopyInput from 'sentry/components/textCopyInput'; import {IconChat, IconFire, IconLink, IconTag} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import type {FeedbackIssue} from 'sentry/utils/feedback/types'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/feedback/feedbackItem/messageSection.tsx b/static/app/components/feedback/feedbackItem/messageSection.tsx index 80cbcd8adc1a5c..e5bdfd55184be3 100644 --- a/static/app/components/feedback/feedbackItem/messageSection.tsx +++ b/static/app/components/feedback/feedbackItem/messageSection.tsx @@ -10,7 +10,7 @@ import {Flex} from 'sentry/components/profiling/flex'; import TimeSince from 'sentry/components/timeSince'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import type {FeedbackIssue} from 'sentry/utils/feedback/types'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/feedback/feedbackItem/useFeedbackActions.ts b/static/app/components/feedback/feedbackItem/useFeedbackActions.ts index b7da47e018bdc4..37eeae099268d1 100644 --- a/static/app/components/feedback/feedbackItem/useFeedbackActions.ts +++ b/static/app/components/feedback/feedbackItem/useFeedbackActions.ts @@ -7,7 +7,7 @@ import { } from 'sentry/actionCreators/indicator'; import useMutateFeedback from 'sentry/components/feedback/useMutateFeedback'; import {t} from 'sentry/locale'; -import {GroupStatus} from 'sentry/types'; +import {GroupStatus} from 'sentry/types/group'; import {trackAnalytics} from 'sentry/utils/analytics'; import type {FeedbackIssue} from 'sentry/utils/feedback/types'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/feedback/feedbackItem/useFeedbackHasScreenshot.tsx b/static/app/components/feedback/feedbackItem/useFeedbackHasScreenshot.tsx index f0bde9a5a4dc88..f2afacc5bab13a 100644 --- a/static/app/components/feedback/feedbackItem/useFeedbackHasScreenshot.tsx +++ b/static/app/components/feedback/feedbackItem/useFeedbackHasScreenshot.tsx @@ -1,7 +1,7 @@ import {useMemo} from 'react'; import {useFetchEventAttachments} from 'sentry/actionCreators/events'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import useOrganization from 'sentry/utils/useOrganization'; interface Props { diff --git a/static/app/components/feedback/hydrateEventTags.tsx b/static/app/components/feedback/hydrateEventTags.tsx index 9c4a7c9fce6764..368028e628efe4 100644 --- a/static/app/components/feedback/hydrateEventTags.tsx +++ b/static/app/components/feedback/hydrateEventTags.tsx @@ -1,4 +1,4 @@ -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; export default function hydrateEventTags( eventData: Event | undefined diff --git a/static/app/components/feedback/list/feedbackListBulkSelection.tsx b/static/app/components/feedback/list/feedbackListBulkSelection.tsx index f307f6453d3f4d..77d500ac4bd585 100644 --- a/static/app/components/feedback/list/feedbackListBulkSelection.tsx +++ b/static/app/components/feedback/list/feedbackListBulkSelection.tsx @@ -8,7 +8,7 @@ import {Flex} from 'sentry/components/profiling/flex'; import {IconEllipsis} from 'sentry/icons/iconEllipsis'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import {GroupStatus} from 'sentry/types'; +import {GroupStatus} from 'sentry/types/group'; import useOrganization from 'sentry/utils/useOrganization'; interface Props diff --git a/static/app/components/feedback/list/useBulkEditFeedbacks.tsx b/static/app/components/feedback/list/useBulkEditFeedbacks.tsx index 4505d28d4e5578..62ae8a3e4f0d0d 100644 --- a/static/app/components/feedback/list/useBulkEditFeedbacks.tsx +++ b/static/app/components/feedback/list/useBulkEditFeedbacks.tsx @@ -9,7 +9,7 @@ import {openConfirmModal} from 'sentry/components/confirm'; import type useListItemCheckboxState from 'sentry/components/feedback/list/useListItemCheckboxState'; import useMutateFeedback from 'sentry/components/feedback/useMutateFeedback'; import {t, tct} from 'sentry/locale'; -import {GroupStatus} from 'sentry/types'; +import {GroupStatus} from 'sentry/types/group'; import {trackAnalytics} from 'sentry/utils/analytics'; import {decodeList} from 'sentry/utils/queryString'; import useLocationQuery from 'sentry/utils/url/useLocationQuery'; diff --git a/static/app/components/feedback/useCurrentFeedbackId.tsx b/static/app/components/feedback/useCurrentFeedbackId.tsx index 11ea4829decece..6de7a9297ea8a0 100644 --- a/static/app/components/feedback/useCurrentFeedbackId.tsx +++ b/static/app/components/feedback/useCurrentFeedbackId.tsx @@ -1,7 +1,7 @@ import {useEffect} from 'react'; import decodeFeedbackSlug from 'sentry/components/feedback/decodeFeedbackSlug'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {useApiQuery} from 'sentry/utils/queryClient'; import {decodeScalar} from 'sentry/utils/queryString'; import useLocationQuery from 'sentry/utils/url/useLocationQuery'; diff --git a/static/app/components/groupPreviewTooltip/utils.tsx b/static/app/components/groupPreviewTooltip/utils.tsx index 8b263eb0230e07..b705c16370eb29 100644 --- a/static/app/components/groupPreviewTooltip/utils.tsx +++ b/static/app/components/groupPreviewTooltip/utils.tsx @@ -1,6 +1,6 @@ import {useCallback, useState} from 'react'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {defined} from 'sentry/utils'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/modals/createTeamModal.tsx b/static/app/components/modals/createTeamModal.tsx index 8ccaa7a8ee7b87..f922e798c81271 100644 --- a/static/app/components/modals/createTeamModal.tsx +++ b/static/app/components/modals/createTeamModal.tsx @@ -4,7 +4,7 @@ import type {ModalRenderProps} from 'sentry/actionCreators/modal'; import {createTeam} from 'sentry/actionCreators/teams'; import CreateTeamForm from 'sentry/components/teams/createTeamForm'; import {t} from 'sentry/locale'; -import type {Organization, Team} from 'sentry/types'; +import type {Organization, Team} from 'sentry/types/organization'; import useApi from 'sentry/utils/useApi'; interface Props extends ModalRenderProps { diff --git a/static/app/components/onboarding/onboardingContext.tsx b/static/app/components/onboarding/onboardingContext.tsx index cf571a7a0da54f..f2366f96fc1d14 100644 --- a/static/app/components/onboarding/onboardingContext.tsx +++ b/static/app/components/onboarding/onboardingContext.tsx @@ -1,6 +1,9 @@ import {createContext, useCallback} from 'react'; -import type {OnboardingProjectStatus, OnboardingSelectedSDK} from 'sentry/types'; +import type { + OnboardingProjectStatus, + OnboardingSelectedSDK, +} from 'sentry/types/onboarding'; import {useSessionStorage} from 'sentry/utils/useSessionStorage'; type Project = { diff --git a/static/app/components/onboarding/productSelection.tsx b/static/app/components/onboarding/productSelection.tsx index d4d475ece1fc00..a5faec39c27f0e 100644 --- a/static/app/components/onboarding/productSelection.tsx +++ b/static/app/components/onboarding/productSelection.tsx @@ -14,7 +14,8 @@ import {IconQuestion} from 'sentry/icons'; import {t, tct} from 'sentry/locale'; import HookStore from 'sentry/stores/hookStore'; import {space} from 'sentry/styles/space'; -import type {Organization, PlatformKey} from 'sentry/types'; +import type {Organization} from 'sentry/types/organization'; +import type {PlatformKey} from 'sentry/types/project'; import {decodeList} from 'sentry/utils/queryString'; import useRouter from 'sentry/utils/useRouter'; import TextBlock from 'sentry/views/settings/components/text/textBlock'; diff --git a/static/app/components/organizations/pageFilters/utils.tsx b/static/app/components/organizations/pageFilters/utils.tsx index d09c505a124dbf..d4abbf37a0f1c5 100644 --- a/static/app/components/organizations/pageFilters/utils.tsx +++ b/static/app/components/organizations/pageFilters/utils.tsx @@ -6,7 +6,7 @@ import pickBy from 'lodash/pickBy'; import {DEFAULT_STATS_PERIOD} from 'sentry/constants'; import {DATE_TIME_KEYS, URL_PARAM} from 'sentry/constants/pageFilters'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; /** * Make a default page filters object diff --git a/static/app/components/profiling/profileHeader.tsx b/static/app/components/profiling/profileHeader.tsx index 138b8dd98518a5..fe0687ff8d4612 100644 --- a/static/app/components/profiling/profileHeader.tsx +++ b/static/app/components/profiling/profileHeader.tsx @@ -8,7 +8,7 @@ import type {ProfilingBreadcrumbsProps} from 'sentry/components/profiling/profil import {ProfilingBreadcrumbs} from 'sentry/components/profiling/profilingBreadcrumbs'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {trackAnalytics} from 'sentry/utils/analytics'; import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls'; import {isSchema, isSentrySampledProfile} from 'sentry/utils/profiling/guards/profile'; diff --git a/static/app/components/profiling/transactionProfileIdProvider.tsx b/static/app/components/profiling/transactionProfileIdProvider.tsx index 1c3073353bd727..8d2bd8360ace33 100644 --- a/static/app/components/profiling/transactionProfileIdProvider.tsx +++ b/static/app/components/profiling/transactionProfileIdProvider.tsx @@ -1,7 +1,7 @@ import {createContext, useContext, useEffect, useMemo} from 'react'; import * as Sentry from '@sentry/react'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {useProfileEvents} from 'sentry/utils/profiling/hooks/useProfileEvents'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/components/repositoryEditForm.tsx b/static/app/components/repositoryEditForm.tsx index 9111ae78618be9..eb963bd373a583 100644 --- a/static/app/components/repositoryEditForm.tsx +++ b/static/app/components/repositoryEditForm.tsx @@ -5,7 +5,7 @@ import Form from 'sentry/components/forms/form'; import type {Field} from 'sentry/components/forms/types'; import ExternalLink from 'sentry/components/links/externalLink'; import {t, tct} from 'sentry/locale'; -import type {Repository} from 'sentry/types'; +import type {Repository} from 'sentry/types/integrations'; type Props = Pick<FormProps, 'onSubmitSuccess' | 'onCancel'> & { closeModal: () => void; diff --git a/static/app/components/repositoryRow.spec.tsx b/static/app/components/repositoryRow.spec.tsx index 976bdf8d39d78d..56c8ed12728b0b 100644 --- a/static/app/components/repositoryRow.spec.tsx +++ b/static/app/components/repositoryRow.spec.tsx @@ -9,7 +9,7 @@ import { } from 'sentry-test/reactTestingLibrary'; import RepositoryRow from 'sentry/components/repositoryRow'; -import {RepositoryStatus} from 'sentry/types'; +import {RepositoryStatus} from 'sentry/types/integrations'; describe('RepositoryRow', function () { beforeEach(function () { diff --git a/static/app/components/repositoryRow.tsx b/static/app/components/repositoryRow.tsx index 1609cf313d2c78..269b57d7ee1ee9 100644 --- a/static/app/components/repositoryRow.tsx +++ b/static/app/components/repositoryRow.tsx @@ -11,8 +11,8 @@ import {Tooltip} from 'sentry/components/tooltip'; import {IconDelete} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Repository} from 'sentry/types'; -import {RepositoryStatus} from 'sentry/types'; +import type {Repository} from 'sentry/types/integrations'; +import {RepositoryStatus} from 'sentry/types/integrations'; type Props = { api: Client; diff --git a/static/app/components/roleSelectControl.tsx b/static/app/components/roleSelectControl.tsx index 0385d50156f256..a30c57dbeabbb9 100644 --- a/static/app/components/roleSelectControl.tsx +++ b/static/app/components/roleSelectControl.tsx @@ -2,7 +2,7 @@ import styled from '@emotion/styled'; import type {ControlProps} from 'sentry/components/forms/controls/selectControl'; import SelectControl from 'sentry/components/forms/controls/selectControl'; -import type {BaseRole} from 'sentry/types'; +import type {BaseRole} from 'sentry/types/organization'; type OptionType = { details: React.ReactNode; diff --git a/static/app/components/timeRangeSelector/index.tsx b/static/app/components/timeRangeSelector/index.tsx index d3a7299000c053..b1be98accb7b91 100644 --- a/static/app/components/timeRangeSelector/index.tsx +++ b/static/app/components/timeRangeSelector/index.tsx @@ -11,7 +11,7 @@ import {DEFAULT_RELATIVE_PERIODS, DEFAULT_STATS_PERIOD} from 'sentry/constants'; import {IconArrow, IconCalendar} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import {trackAnalytics} from 'sentry/utils/analytics'; import { getDateWithTimezoneInUtc, diff --git a/static/app/components/timeRangeSelector/utils.tsx b/static/app/components/timeRangeSelector/utils.tsx index 4eb07939e878ce..2d1e961d5609d3 100644 --- a/static/app/components/timeRangeSelector/utils.tsx +++ b/static/app/components/timeRangeSelector/utils.tsx @@ -6,7 +6,7 @@ import autoCompleteFilter from 'sentry/components/dropdownAutoComplete/autoCompl import type {ItemsBeforeFilter} from 'sentry/components/dropdownAutoComplete/types'; import {DEFAULT_RELATIVE_PERIODS} from 'sentry/constants'; import {t, tn} from 'sentry/locale'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import { DEFAULT_DAY_END_TIME, DEFAULT_DAY_START_TIME, diff --git a/static/app/data/forms/organizationGeneralSettings.tsx b/static/app/data/forms/organizationGeneralSettings.tsx index a5edef6d70990a..792b4bf450c25a 100644 --- a/static/app/data/forms/organizationGeneralSettings.tsx +++ b/static/app/data/forms/organizationGeneralSettings.tsx @@ -1,7 +1,7 @@ import type {JsonFormObject} from 'sentry/components/forms/types'; import ExternalLink from 'sentry/components/links/externalLink'; import {t, tct} from 'sentry/locale'; -import type {BaseRole} from 'sentry/types'; +import type {BaseRole} from 'sentry/types/organization'; import slugify from 'sentry/utils/slugify'; // Export route to make these forms searchable by label/help diff --git a/static/app/data/platforms.tsx b/static/app/data/platforms.tsx index 18da3de342ad14..6749dfa83dc7a7 100644 --- a/static/app/data/platforms.tsx +++ b/static/app/data/platforms.tsx @@ -1,4 +1,4 @@ -import type {PlatformIntegration} from 'sentry/types'; +import type {PlatformIntegration} from 'sentry/types/project'; // If you update items of this list, please remember to update the "GETTING_STARTED_DOCS_PLATFORMS" list // in the 'src/sentry/models/project.py' file. This way, they'll work together correctly. diff --git a/static/app/data/timezones.tsx b/static/app/data/timezones.tsx index e3fd97da41bfb2..7aeaeacb33d167 100644 --- a/static/app/data/timezones.tsx +++ b/static/app/data/timezones.tsx @@ -2,7 +2,7 @@ import styled from '@emotion/styled'; import groupBy from 'lodash/groupBy'; import moment from 'moment-timezone'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; type TimezoneGroup = | null diff --git a/static/app/utils/dates.tsx b/static/app/utils/dates.tsx index 1e65cd31fc9666..aeb5da481350de 100644 --- a/static/app/utils/dates.tsx +++ b/static/app/utils/dates.tsx @@ -2,7 +2,7 @@ import moment from 'moment'; import {parseStatsPeriod} from 'sentry/components/organizations/pageFilters/parse'; import ConfigStore from 'sentry/stores/configStore'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type {TableDataRow} from './discover/discoverQuery'; diff --git a/static/app/utils/getPeriod.tsx b/static/app/utils/getPeriod.tsx index 692528aa9df664..7b14fe10766769 100644 --- a/static/app/utils/getPeriod.tsx +++ b/static/app/utils/getPeriod.tsx @@ -1,7 +1,7 @@ import moment from 'moment'; import {DEFAULT_STATS_PERIOD} from 'sentry/constants'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import {getUtcDateString} from 'sentry/utils/dates'; type DateObject = { diff --git a/static/app/utils/metrics/constants.tsx b/static/app/utils/metrics/constants.tsx index 276d7b935bfe74..b8bb641561de29 100644 --- a/static/app/utils/metrics/constants.tsx +++ b/static/app/utils/metrics/constants.tsx @@ -1,5 +1,5 @@ import {t} from 'sentry/locale'; -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import type { MetricsEquationWidget, MetricsQueryWidget, diff --git a/static/app/utils/metrics/dashboard.tsx b/static/app/utils/metrics/dashboard.tsx index 4bbf3a320ef448..958872fc73dd28 100644 --- a/static/app/utils/metrics/dashboard.tsx +++ b/static/app/utils/metrics/dashboard.tsx @@ -1,6 +1,6 @@ import {urlEncode} from '@sentry/utils'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {defined} from 'sentry/utils'; import {MRIToField} from 'sentry/utils/metrics/mri'; import type {MetricDisplayType, MetricsQuery} from 'sentry/utils/metrics/types'; diff --git a/static/app/utils/metrics/index.tsx b/static/app/utils/metrics/index.tsx index 25a9fbd03bc107..4029aa9e076809 100644 --- a/static/app/utils/metrics/index.tsx +++ b/static/app/utils/metrics/index.tsx @@ -20,7 +20,7 @@ import { parseStatsPeriod, } from 'sentry/components/organizations/pageFilters/parse'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type { MetricMeta, MetricsDataIntervalLadder, diff --git a/static/app/utils/metrics/useIncrementQueryMetric.tsx b/static/app/utils/metrics/useIncrementQueryMetric.tsx index 11bfdc7fba2684..d210c8b62c8a86 100644 --- a/static/app/utils/metrics/useIncrementQueryMetric.tsx +++ b/static/app/utils/metrics/useIncrementQueryMetric.tsx @@ -1,7 +1,7 @@ import {useCallback} from 'react'; import * as Sentry from '@sentry/react'; -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import {getReadableMetricType} from 'sentry/utils/metrics/formatters'; import {parseMRI} from 'sentry/utils/metrics/mri'; diff --git a/static/app/utils/metrics/useMetricsCodeLocations.tsx b/static/app/utils/metrics/useMetricsCodeLocations.tsx index 9cdd973b09faa4..397dc56c3bb0ab 100644 --- a/static/app/utils/metrics/useMetricsCodeLocations.tsx +++ b/static/app/utils/metrics/useMetricsCodeLocations.tsx @@ -1,4 +1,4 @@ -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import {getDateTimeParams} from 'sentry/utils/metrics'; import type {MetricMetaCodeLocation} from 'sentry/utils/metrics/types'; import {useApiQuery} from 'sentry/utils/queryClient'; diff --git a/static/app/utils/metrics/useMetricsMeta.tsx b/static/app/utils/metrics/useMetricsMeta.tsx index 99e35dae93c5cb..5647b468ea8b2d 100644 --- a/static/app/utils/metrics/useMetricsMeta.tsx +++ b/static/app/utils/metrics/useMetricsMeta.tsx @@ -1,6 +1,6 @@ import {useMemo} from 'react'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {formatMRI, getUseCaseFromMRI} from 'sentry/utils/metrics/mri'; import type {ApiQueryKey} from 'sentry/utils/queryClient'; import {useApiQueries} from 'sentry/utils/queryClient'; diff --git a/static/app/utils/metrics/useMetricsQuery.tsx b/static/app/utils/metrics/useMetricsQuery.tsx index 3c26da994dec60..9434449cbfa4b7 100644 --- a/static/app/utils/metrics/useMetricsQuery.tsx +++ b/static/app/utils/metrics/useMetricsQuery.tsx @@ -1,6 +1,6 @@ import {useMemo} from 'react'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {parsePeriodToHours} from 'sentry/utils/dates'; import {getDateTimeParams, getMetricsInterval} from 'sentry/utils/metrics'; import {getUseCaseFromMRI, MRIToField} from 'sentry/utils/metrics/mri'; diff --git a/static/app/utils/performance/histogram/constants.tsx b/static/app/utils/performance/histogram/constants.tsx index 8d88cb9c012711..059afe60c80920 100644 --- a/static/app/utils/performance/histogram/constants.tsx +++ b/static/app/utils/performance/histogram/constants.tsx @@ -1,5 +1,5 @@ import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import type {DataFilter} from './types'; diff --git a/static/app/utils/performance/histogram/index.tsx b/static/app/utils/performance/histogram/index.tsx index 0c0f5357901ec3..ffc1d0aafc5fb8 100644 --- a/static/app/utils/performance/histogram/index.tsx +++ b/static/app/utils/performance/histogram/index.tsx @@ -2,7 +2,7 @@ import {Component} from 'react'; import {browserHistory} from 'react-router'; import type {Location} from 'history'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {decodeScalar} from 'sentry/utils/queryString'; import {FILTER_OPTIONS} from './constants'; diff --git a/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts index f22cdb7a95976b..a8e43d3444ac08 100644 --- a/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts +++ b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts @@ -1,7 +1,7 @@ import {useMemo} from 'react'; import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {UseApiQueryResult} from 'sentry/utils/queryClient'; import {useApiQuery} from 'sentry/utils/queryClient'; import type RequestError from 'sentry/utils/requestError/requestError'; diff --git a/static/app/utils/profiling/hooks/useProfileEvents.tsx b/static/app/utils/profiling/hooks/useProfileEvents.tsx index df408a227c7b30..9eb6f57add8725 100644 --- a/static/app/utils/profiling/hooks/useProfileEvents.tsx +++ b/static/app/utils/profiling/hooks/useProfileEvents.tsx @@ -1,6 +1,6 @@ import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {defined} from 'sentry/utils'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/utils/profiling/hooks/useProfileFunctionTrends.tsx b/static/app/utils/profiling/hooks/useProfileFunctionTrends.tsx index 98abd089ec5571..4932288e6bd7b5 100644 --- a/static/app/utils/profiling/hooks/useProfileFunctionTrends.tsx +++ b/static/app/utils/profiling/hooks/useProfileFunctionTrends.tsx @@ -1,5 +1,5 @@ import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; import usePageFilters from 'sentry/utils/usePageFilters'; diff --git a/static/app/utils/profiling/hooks/useProfileFunctions.tsx b/static/app/utils/profiling/hooks/useProfileFunctions.tsx index 377d1ad2a7c4d5..2cc3d2ff5bc4c6 100644 --- a/static/app/utils/profiling/hooks/useProfileFunctions.tsx +++ b/static/app/utils/profiling/hooks/useProfileFunctions.tsx @@ -1,5 +1,5 @@ import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; import usePageFilters from 'sentry/utils/usePageFilters'; diff --git a/static/app/utils/profiling/hooks/useRelativeDateTime.tsx b/static/app/utils/profiling/hooks/useRelativeDateTime.tsx index 3391bdeb263a37..c4b894a342f596 100644 --- a/static/app/utils/profiling/hooks/useRelativeDateTime.tsx +++ b/static/app/utils/profiling/hooks/useRelativeDateTime.tsx @@ -1,6 +1,6 @@ import {useMemo} from 'react'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {getUserTimezone} from 'sentry/utils/dates'; const DAY = 24 * 60 * 60 * 1000; diff --git a/static/app/utils/releases/releasesProvider.spec.tsx b/static/app/utils/releases/releasesProvider.spec.tsx index ef6a395c0505f8..5fb3738648f93b 100644 --- a/static/app/utils/releases/releasesProvider.spec.tsx +++ b/static/app/utils/releases/releasesProvider.spec.tsx @@ -3,7 +3,7 @@ import {ReleaseFixture} from 'sentry-fixture/release'; import {initializeOrg} from 'sentry-test/initializeOrg'; import {render, screen} from 'sentry-test/reactTestingLibrary'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {ReleasesProvider, useReleases} from 'sentry/utils/releases/releasesProvider'; function TestComponent({other}: {other: string}) { diff --git a/static/app/utils/replays/getReplayIdFromEvent.tsx b/static/app/utils/replays/getReplayIdFromEvent.tsx index 465a6a98b4baa9..e893e0e55e2415 100644 --- a/static/app/utils/replays/getReplayIdFromEvent.tsx +++ b/static/app/utils/replays/getReplayIdFromEvent.tsx @@ -1,4 +1,4 @@ -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; export function getReplayIdFromEvent(event: Event | null | undefined) { const replayTagId = event?.tags?.find(({key}) => key === 'replayId')?.value; diff --git a/static/app/utils/withPageFilters.spec.tsx b/static/app/utils/withPageFilters.spec.tsx index 466439a05c181b..6577a8d3ace4c8 100644 --- a/static/app/utils/withPageFilters.spec.tsx +++ b/static/app/utils/withPageFilters.spec.tsx @@ -1,7 +1,7 @@ import {act, render, screen} from 'sentry-test/reactTestingLibrary'; import PageFiltersStore from 'sentry/stores/pageFiltersStore'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import withPageFilters from 'sentry/utils/withPageFilters'; describe('withPageFilters HoC', function () { diff --git a/static/app/utils/withPageFilters.tsx b/static/app/utils/withPageFilters.tsx index e32109b5f505f6..59b082faa3a388 100644 --- a/static/app/utils/withPageFilters.tsx +++ b/static/app/utils/withPageFilters.tsx @@ -1,4 +1,4 @@ -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import getDisplayName from 'sentry/utils/getDisplayName'; import usePageFilters from './usePageFilters'; diff --git a/static/app/utils/withSavedSearches.tsx b/static/app/utils/withSavedSearches.tsx index 7f8abf58e3a275..716896a2a6ba24 100644 --- a/static/app/utils/withSavedSearches.tsx +++ b/static/app/utils/withSavedSearches.tsx @@ -1,6 +1,6 @@ import type {RouteComponentProps} from 'react-router'; -import type {SavedSearch} from 'sentry/types'; +import type {SavedSearch} from 'sentry/types/group'; import useOrganization from 'sentry/utils/useOrganization'; import {useParams} from 'sentry/utils/useParams'; import {useFetchSavedSearchesForOrg} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg'; diff --git a/static/app/views/alerts/builder/projectProvider.tsx b/static/app/views/alerts/builder/projectProvider.tsx index 7e0302495241ac..9e596d009a3321 100644 --- a/static/app/views/alerts/builder/projectProvider.tsx +++ b/static/app/views/alerts/builder/projectProvider.tsx @@ -6,7 +6,7 @@ import {navigateTo} from 'sentry/actionCreators/navigation'; import {Alert} from 'sentry/components/alert'; import LoadingIndicator from 'sentry/components/loadingIndicator'; import {t} from 'sentry/locale'; -import type {Member, Organization} from 'sentry/types'; +import type {Member, Organization} from 'sentry/types/organization'; import useApi from 'sentry/utils/useApi'; import {useIsMountedRef} from 'sentry/utils/useIsMountedRef'; import useProjects from 'sentry/utils/useProjects'; diff --git a/static/app/views/alerts/list/incidents/row.tsx b/static/app/views/alerts/list/incidents/row.tsx index b9bed443c7f287..583e03072d73f0 100644 --- a/static/app/views/alerts/list/incidents/row.tsx +++ b/static/app/views/alerts/list/incidents/row.tsx @@ -12,7 +12,9 @@ import TimeSince from 'sentry/components/timeSince'; import {t} from 'sentry/locale'; import TeamStore from 'sentry/stores/teamStore'; import {space} from 'sentry/styles/space'; -import type {Actor, Organization, Project} from 'sentry/types'; +import type {Actor} from 'sentry/types/core'; +import type {Organization} from 'sentry/types/organization'; +import type {Project} from 'sentry/types/project'; import getDynamicText from 'sentry/utils/getDynamicText'; import type {Incident} from 'sentry/views/alerts/types'; import {IncidentStatus} from 'sentry/views/alerts/types'; diff --git a/static/app/views/alerts/rules/issue/details/ruleDetails.tsx b/static/app/views/alerts/rules/issue/details/ruleDetails.tsx index cf1c623e9d1681..50c7e1874f14a1 100644 --- a/static/app/views/alerts/rules/issue/details/ruleDetails.tsx +++ b/static/app/views/alerts/rules/issue/details/ruleDetails.tsx @@ -27,9 +27,9 @@ import TimeSince from 'sentry/components/timeSince'; import {IconCopy, IconEdit} from 'sentry/icons'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {DateString} from 'sentry/types'; import type {IssueAlertRule} from 'sentry/types/alerts'; import {RuleActionsCategories} from 'sentry/types/alerts'; +import type {DateString} from 'sentry/types/core'; import {trackAnalytics} from 'sentry/utils/analytics'; import type {ApiQueryKey} from 'sentry/utils/queryClient'; import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient'; diff --git a/static/app/views/alerts/rules/metric/details/constants.tsx b/static/app/views/alerts/rules/metric/details/constants.tsx index 6eb1ecb9c0995e..c4adcfc258d51f 100644 --- a/static/app/views/alerts/rules/metric/details/constants.tsx +++ b/static/app/views/alerts/rules/metric/details/constants.tsx @@ -1,5 +1,5 @@ import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {TimePeriod, TimeWindow} from 'sentry/views/alerts/rules/metric/types'; export const SELECTOR_RELATIVE_PERIODS = { diff --git a/static/app/views/alerts/rules/metric/triggers/chart/thresholdsChart.tsx b/static/app/views/alerts/rules/metric/triggers/chart/thresholdsChart.tsx index 57340f08c55851..66d5868e945161 100644 --- a/static/app/views/alerts/rules/metric/triggers/chart/thresholdsChart.tsx +++ b/static/app/views/alerts/rules/metric/triggers/chart/thresholdsChart.tsx @@ -12,7 +12,7 @@ import LineSeries from 'sentry/components/charts/series/lineSeries'; import {DEFAULT_STATS_PERIOD} from 'sentry/constants'; import {CHART_PALETTE} from 'sentry/constants/chartPalette'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {ReactEchartsRef, Series} from 'sentry/types/echarts'; import theme from 'sentry/utils/theme'; import { diff --git a/static/app/views/alerts/wizard/options.tsx b/static/app/views/alerts/wizard/options.tsx index 1b12be981be010..5473a48b74fc52 100644 --- a/static/app/views/alerts/wizard/options.tsx +++ b/static/app/views/alerts/wizard/options.tsx @@ -1,7 +1,8 @@ import mapValues from 'lodash/mapValues'; import {t} from 'sentry/locale'; -import type {Organization, TagCollection} from 'sentry/types'; +import type {TagCollection} from 'sentry/types/group'; +import type {Organization} from 'sentry/types/organization'; import { FieldKey, makeTagCollection, diff --git a/static/app/views/dashboards/datasetConfig/issues.spec.tsx b/static/app/views/dashboards/datasetConfig/issues.spec.tsx index d6ae6a6be48fad..2f818b252154dd 100644 --- a/static/app/views/dashboards/datasetConfig/issues.spec.tsx +++ b/static/app/views/dashboards/datasetConfig/issues.spec.tsx @@ -3,7 +3,7 @@ import {GroupFixture} from 'sentry-fixture/group'; import {OrganizationFixture} from 'sentry-fixture/organization'; import {ProjectFixture} from 'sentry-fixture/project'; -import {GroupStatus} from 'sentry/types'; +import {GroupStatus} from 'sentry/types/group'; import {transformIssuesResponseToTable} from 'sentry/views/dashboards/datasetConfig/issues'; describe('transformIssuesResponseToTable', function () { diff --git a/static/app/views/dashboards/manage/index.tsx b/static/app/views/dashboards/manage/index.tsx index fd2d34e760b3a8..fe40301c671dab 100644 --- a/static/app/views/dashboards/manage/index.tsx +++ b/static/app/views/dashboards/manage/index.tsx @@ -23,7 +23,8 @@ import Switch from 'sentry/components/switchButton'; import {IconAdd, IconDownload} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Organization, SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; +import type {Organization} from 'sentry/types/organization'; import {trackAnalytics} from 'sentry/utils/analytics'; import {hasDashboardImportFeature} from 'sentry/utils/metrics/features'; import {decodeScalar} from 'sentry/utils/queryString'; diff --git a/static/app/views/dashboards/metrics/utils.tsx b/static/app/views/dashboards/metrics/utils.tsx index d3c7a4510bbcee..85d9a2117f180e 100644 --- a/static/app/views/dashboards/metrics/utils.tsx +++ b/static/app/views/dashboards/metrics/utils.tsx @@ -1,6 +1,6 @@ import {useMemo} from 'react'; -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import {unescapeMetricsFormula} from 'sentry/utils/metrics'; import {NO_QUERY_ID} from 'sentry/utils/metrics/constants'; import {formatMRIField, MRIToField, parseField} from 'sentry/utils/metrics/mri'; diff --git a/static/app/views/dashboards/widgetBuilder/buildSteps/columnsStep/index.tsx b/static/app/views/dashboards/widgetBuilder/buildSteps/columnsStep/index.tsx index 16f833888b3025..aa1a76106ce694 100644 --- a/static/app/views/dashboards/widgetBuilder/buildSteps/columnsStep/index.tsx +++ b/static/app/views/dashboards/widgetBuilder/buildSteps/columnsStep/index.tsx @@ -1,6 +1,7 @@ import ExternalLink from 'sentry/components/links/externalLink'; import {t, tct} from 'sentry/locale'; -import type {Organization, TagCollection} from 'sentry/types'; +import type {TagCollection} from 'sentry/types/group'; +import type {Organization} from 'sentry/types/organization'; import type {QueryFieldValue} from 'sentry/utils/discover/fields'; import useCustomMeasurements from 'sentry/utils/useCustomMeasurements'; import {getDatasetConfig} from 'sentry/views/dashboards/datasetConfig/base'; diff --git a/static/app/views/dashboards/widgetBuilder/buildSteps/visualizationStep.tsx b/static/app/views/dashboards/widgetBuilder/buildSteps/visualizationStep.tsx index aa9cb6b3eed107..0f77f002bbaa33 100644 --- a/static/app/views/dashboards/widgetBuilder/buildSteps/visualizationStep.tsx +++ b/static/app/views/dashboards/widgetBuilder/buildSteps/visualizationStep.tsx @@ -13,7 +13,8 @@ import PanelAlert from 'sentry/components/panels/panelAlert'; import {DEFAULT_DEBOUNCE_DURATION} from 'sentry/constants'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Organization, PageFilters, SelectValue} from 'sentry/types'; +import type {PageFilters, SelectValue} from 'sentry/types/core'; +import type {Organization} from 'sentry/types/organization'; import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery'; import usePrevious from 'sentry/utils/usePrevious'; import type {DashboardFilters, Widget} from 'sentry/views/dashboards/types'; diff --git a/static/app/views/dashboards/widgetBuilder/issueWidget/utils.tsx b/static/app/views/dashboards/widgetBuilder/issueWidget/utils.tsx index e659a8c85c8ced..fb437f81851d05 100644 --- a/static/app/views/dashboards/widgetBuilder/issueWidget/utils.tsx +++ b/static/app/views/dashboards/widgetBuilder/issueWidget/utils.tsx @@ -1,4 +1,4 @@ -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import type {FieldValue} from 'sentry/views/discover/table/types'; import {FieldValueKind} from 'sentry/views/discover/table/types'; import {getSortLabel, IssueSortOptions} from 'sentry/views/issueList/utils'; diff --git a/static/app/views/dashboards/widgetCard/issueWidgetCard.tsx b/static/app/views/dashboards/widgetCard/issueWidgetCard.tsx index 48239aa5036aea..f555b8c807fd2a 100644 --- a/static/app/views/dashboards/widgetCard/issueWidgetCard.tsx +++ b/static/app/views/dashboards/widgetCard/issueWidgetCard.tsx @@ -6,7 +6,7 @@ import SimpleTableChart from 'sentry/components/charts/simpleTableChart'; import Placeholder from 'sentry/components/placeholder'; import {IconWarning} from 'sentry/icons'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {defined} from 'sentry/utils'; import type {TableDataRow} from 'sentry/utils/discover/discoverQuery'; import {eventViewFromWidget} from 'sentry/views/dashboards/utils'; diff --git a/static/app/views/dashboards/widgetCard/widgetQueries.spec.tsx b/static/app/views/dashboards/widgetCard/widgetQueries.spec.tsx index 7aaa3bfc22f58a..9ad35ee473e29a 100644 --- a/static/app/views/dashboards/widgetCard/widgetQueries.spec.tsx +++ b/static/app/views/dashboards/widgetCard/widgetQueries.spec.tsx @@ -4,7 +4,7 @@ import {OrganizationFixture} from 'sentry-fixture/organization'; import {initializeOrg} from 'sentry-test/initializeOrg'; import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {MetricsResultsMetaProvider} from 'sentry/utils/performance/contexts/metricsEnhancedPerformanceDataContext'; import {MEPSettingProvider} from 'sentry/utils/performance/contexts/metricsEnhancedSetting'; import {DashboardFilterKeys, DisplayType} from 'sentry/views/dashboards/types'; diff --git a/static/app/views/discover/chartFooter.tsx b/static/app/views/discover/chartFooter.tsx index d9dff892b0278d..9a3dd11bc59fa4 100644 --- a/static/app/views/discover/chartFooter.tsx +++ b/static/app/views/discover/chartFooter.tsx @@ -7,7 +7,7 @@ import { SectionValue, } from 'sentry/components/charts/styles'; import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import type EventView from 'sentry/utils/discover/eventView'; import {TOP_EVENT_MODES} from 'sentry/utils/discover/types'; diff --git a/static/app/views/discover/table/queryField.tsx b/static/app/views/discover/table/queryField.tsx index d2171c3711c068..18a2561145b503 100644 --- a/static/app/views/discover/table/queryField.tsx +++ b/static/app/views/discover/table/queryField.tsx @@ -14,7 +14,7 @@ import {IconWarning} from 'sentry/icons'; import {t} from 'sentry/locale'; import {pulse} from 'sentry/styles/animations'; import {space} from 'sentry/styles/space'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import type { AggregateParameter, AggregationKeyWithAlias, diff --git a/static/app/views/discover/table/quickContext/issueContext.spec.tsx b/static/app/views/discover/table/quickContext/issueContext.spec.tsx index 202d23205b043f..d232f274f78b34 100644 --- a/static/app/views/discover/table/quickContext/issueContext.spec.tsx +++ b/static/app/views/discover/table/quickContext/issueContext.spec.tsx @@ -6,7 +6,7 @@ import {RepositoryFixture} from 'sentry-fixture/repository'; import {makeTestQueryClient} from 'sentry-test/queryClient'; import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; -import {GroupStatus} from 'sentry/types'; +import {GroupStatus} from 'sentry/types/group'; import type {EventData} from 'sentry/utils/discover/eventView'; import {QueryClientProvider} from 'sentry/utils/queryClient'; diff --git a/static/app/views/issueDetails/traceTimeline/traceLink.tsx b/static/app/views/issueDetails/traceTimeline/traceLink.tsx index dffa4a005fb842..2a5321fd223cad 100644 --- a/static/app/views/issueDetails/traceTimeline/traceLink.tsx +++ b/static/app/views/issueDetails/traceTimeline/traceLink.tsx @@ -7,7 +7,7 @@ import {generateTraceTarget} from 'sentry/components/quickTrace/utils'; import {IconChevron} from 'sentry/icons'; import {t, tn} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {trackAnalytics} from 'sentry/utils/analytics'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/views/issueDetails/traceTimeline/traceTimeline.tsx b/static/app/views/issueDetails/traceTimeline/traceTimeline.tsx index cb1126078d1afa..fd104105395a06 100644 --- a/static/app/views/issueDetails/traceTimeline/traceTimeline.tsx +++ b/static/app/views/issueDetails/traceTimeline/traceTimeline.tsx @@ -5,7 +5,7 @@ import ErrorBoundary from 'sentry/components/errorBoundary'; import QuestionTooltip from 'sentry/components/questionTooltip'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams'; import {useDimensions} from 'sentry/utils/useDimensions'; diff --git a/static/app/views/issueDetails/traceTimeline/traceTimelineEvents.tsx b/static/app/views/issueDetails/traceTimeline/traceTimelineEvents.tsx index 60194ba695ca1f..7dc75715268e04 100644 --- a/static/app/views/issueDetails/traceTimeline/traceTimelineEvents.tsx +++ b/static/app/views/issueDetails/traceTimeline/traceTimelineEvents.tsx @@ -6,7 +6,7 @@ import {DateTime} from 'sentry/components/dateTime'; import {Tooltip} from 'sentry/components/tooltip'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {TraceTimelineTooltip} from 'sentry/views/issueDetails/traceTimeline/traceTimelineTooltip'; import type {TimelineEvent} from './useTraceTimelineEvents'; diff --git a/static/app/views/issueDetails/traceTimeline/traceTimelineTooltip.tsx b/static/app/views/issueDetails/traceTimeline/traceTimelineTooltip.tsx index 668b6a17cfc4b4..ebbf6ba558d90f 100644 --- a/static/app/views/issueDetails/traceTimeline/traceTimelineTooltip.tsx +++ b/static/app/views/issueDetails/traceTimeline/traceTimelineTooltip.tsx @@ -5,7 +5,7 @@ import Link from 'sentry/components/links/link'; import {generateTraceTarget} from 'sentry/components/quickTrace/utils'; import {t, tn} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {trackAnalytics} from 'sentry/utils/analytics'; import {useLocation} from 'sentry/utils/useLocation'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx b/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx index 38a75af356c2af..28e02107398222 100644 --- a/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx +++ b/static/app/views/issueDetails/traceTimeline/useTraceTimelineEvents.tsx @@ -1,6 +1,6 @@ import {useMemo} from 'react'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {DiscoverDatasets} from 'sentry/utils/discover/types'; import {getTraceTimeRangeFromEvent} from 'sentry/utils/performance/quickTrace/utils'; import {useApiQuery} from 'sentry/utils/queryClient'; diff --git a/static/app/views/issueList/actions/actionSet.tsx b/static/app/views/issueList/actions/actionSet.tsx index e7369ed53b6268..42b7878673a7ee 100644 --- a/static/app/views/issueList/actions/actionSet.tsx +++ b/static/app/views/issueList/actions/actionSet.tsx @@ -10,8 +10,8 @@ import {DropdownMenu} from 'sentry/components/dropdownMenu'; import {IconEllipsis} from 'sentry/icons'; import {t} from 'sentry/locale'; import GroupStore from 'sentry/stores/groupStore'; -import type {BaseGroup} from 'sentry/types'; -import {GroupStatus} from 'sentry/types'; +import type {BaseGroup} from 'sentry/types/group'; +import {GroupStatus} from 'sentry/types/group'; import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig'; import type {IssueTypeConfig} from 'sentry/utils/issueTypeConfig/types'; import useMedia from 'sentry/utils/useMedia'; diff --git a/static/app/views/issueList/actions/headers.tsx b/static/app/views/issueList/actions/headers.tsx index 14fc920f5fa029..84b983375de8fd 100644 --- a/static/app/views/issueList/actions/headers.tsx +++ b/static/app/views/issueList/actions/headers.tsx @@ -4,7 +4,7 @@ import styled from '@emotion/styled'; import ToolbarHeader from 'sentry/components/toolbarHeader'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import useOrganization from 'sentry/utils/useOrganization'; type Props = { diff --git a/static/app/views/issueList/actions/index.tsx b/static/app/views/issueList/actions/index.tsx index 66ced022bf1e3b..69b91b6496129b 100644 --- a/static/app/views/issueList/actions/index.tsx +++ b/static/app/views/issueList/actions/index.tsx @@ -17,7 +17,8 @@ import ProjectsStore from 'sentry/stores/projectsStore'; import SelectedGroupStore from 'sentry/stores/selectedGroupStore'; import {useLegacyStore} from 'sentry/stores/useLegacyStore'; import {space} from 'sentry/styles/space'; -import type {Group, PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; +import type {Group} from 'sentry/types/group'; import {trackAnalytics} from 'sentry/utils/analytics'; import {uniq} from 'sentry/utils/array/uniq'; import {useQueryClient} from 'sentry/utils/queryClient'; diff --git a/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx b/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx index d604b7387cec1a..4e8e644f2eadcf 100644 --- a/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx +++ b/static/app/views/issueList/mutations/useDeleteSavedSearch.tsx @@ -1,6 +1,6 @@ import {addErrorMessage} from 'sentry/actionCreators/indicator'; import {t} from 'sentry/locale'; -import type {SavedSearch} from 'sentry/types'; +import type {SavedSearch} from 'sentry/types/group'; import type {UseMutationOptions} from 'sentry/utils/queryClient'; import { getApiQueryData, diff --git a/static/app/views/issueList/overview.actions.spec.tsx b/static/app/views/issueList/overview.actions.spec.tsx index 0997da26d2763c..87d620594a8d43 100644 --- a/static/app/views/issueList/overview.actions.spec.tsx +++ b/static/app/views/issueList/overview.actions.spec.tsx @@ -21,7 +21,7 @@ import GroupStore from 'sentry/stores/groupStore'; import IssueListCacheStore from 'sentry/stores/IssueListCacheStore'; import SelectedGroupStore from 'sentry/stores/selectedGroupStore'; import TagStore from 'sentry/stores/tagStore'; -import {PriorityLevel} from 'sentry/types'; +import {PriorityLevel} from 'sentry/types/group'; import IssueListOverview from 'sentry/views/issueList/overview'; const DEFAULT_LINKS_HEADER = diff --git a/static/app/views/issueList/queries/useFetchSavedSearchesForOrg.tsx b/static/app/views/issueList/queries/useFetchSavedSearchesForOrg.tsx index afc456cb38083d..dc2496a49b3ea1 100644 --- a/static/app/views/issueList/queries/useFetchSavedSearchesForOrg.tsx +++ b/static/app/views/issueList/queries/useFetchSavedSearchesForOrg.tsx @@ -1,4 +1,4 @@ -import type {SavedSearch} from 'sentry/types'; +import type {SavedSearch} from 'sentry/types/group'; import type {UseApiQueryOptions} from 'sentry/utils/queryClient'; import {useApiQuery} from 'sentry/utils/queryClient'; diff --git a/static/app/views/issueList/utils/parseIssuePrioritySearch.tsx b/static/app/views/issueList/utils/parseIssuePrioritySearch.tsx index 0593cf4ba1bc5a..6b372737cb03e4 100644 --- a/static/app/views/issueList/utils/parseIssuePrioritySearch.tsx +++ b/static/app/views/issueList/utils/parseIssuePrioritySearch.tsx @@ -1,6 +1,6 @@ import type {TokenResult} from 'sentry/components/searchSyntax/parser'; import {parseSearch, Token} from 'sentry/components/searchSyntax/parser'; -import {PriorityLevel} from 'sentry/types'; +import {PriorityLevel} from 'sentry/types/group'; const VALID_PRIORITIES = new Set([ PriorityLevel.HIGH, diff --git a/static/app/views/issueList/utils/useSelectedSavedSearch.tsx b/static/app/views/issueList/utils/useSelectedSavedSearch.tsx index b0cb0bfbcb5026..7b3fe97f695cf2 100644 --- a/static/app/views/issueList/utils/useSelectedSavedSearch.tsx +++ b/static/app/views/issueList/utils/useSelectedSavedSearch.tsx @@ -1,7 +1,7 @@ import {useMemo} from 'react'; import {t} from 'sentry/locale'; -import type {SavedSearch} from 'sentry/types'; +import type {SavedSearch} from 'sentry/types/group'; import {useLocation} from 'sentry/utils/useLocation'; import useOrganization from 'sentry/utils/useOrganization'; import {useParams} from 'sentry/utils/useParams'; diff --git a/static/app/views/metrics/chart/types.tsx b/static/app/views/metrics/chart/types.tsx index cd11c18783c7b5..48ea65bf55633d 100644 --- a/static/app/views/metrics/chart/types.tsx +++ b/static/app/views/metrics/chart/types.tsx @@ -1,5 +1,5 @@ import type {BaseChartProps} from 'sentry/components/charts/baseChart'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type {MetricDisplayType} from 'sentry/utils/metrics/types'; export type Series = { diff --git a/static/app/views/metrics/chart/useFocusArea.tsx b/static/app/views/metrics/chart/useFocusArea.tsx index 239e4e82cc8e7e..1df957748b1e82 100644 --- a/static/app/views/metrics/chart/useFocusArea.tsx +++ b/static/app/views/metrics/chart/useFocusArea.tsx @@ -11,7 +11,7 @@ import {Button} from 'sentry/components/button'; import type {DateTimeObject} from 'sentry/components/charts/utils'; import {IconClose, IconZoom} from 'sentry/icons'; import {space} from 'sentry/styles/space'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type {EChartBrushEndHandler, ReactEchartsRef} from 'sentry/types/echarts'; import mergeRefs from 'sentry/utils/mergeRefs'; import type {ValueRect} from 'sentry/views/metrics/chart/chartUtils'; diff --git a/static/app/views/metrics/chart/useMetricReleases.tsx b/static/app/views/metrics/chart/useMetricReleases.tsx index 5296dda2060015..1419a7e8386a5c 100644 --- a/static/app/views/metrics/chart/useMetricReleases.tsx +++ b/static/app/views/metrics/chart/useMetricReleases.tsx @@ -4,7 +4,7 @@ import {useTheme} from '@emotion/react'; import {addErrorMessage} from 'sentry/actionCreators/indicator'; import MarkLine from 'sentry/components/charts/components/markLine'; import {t} from 'sentry/locale'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import {escape} from 'sentry/utils'; import {getFormattedDate, getTimeFormat, getUtcDateString} from 'sentry/utils/dates'; import {formatVersion} from 'sentry/utils/formatters'; diff --git a/static/app/views/metrics/ddmOnboarding/sidebar.tsx b/static/app/views/metrics/ddmOnboarding/sidebar.tsx index fbdcc26ec8d99a..0a303398f46ac5 100644 --- a/static/app/views/metrics/ddmOnboarding/sidebar.tsx +++ b/static/app/views/metrics/ddmOnboarding/sidebar.tsx @@ -18,7 +18,8 @@ import { import platforms from 'sentry/data/platforms'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Project, SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; +import type {Project} from 'sentry/types/project'; import {METRICS_DOCS_URL} from 'sentry/utils/metrics/constants'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/views/metrics/utils/index.spec.tsx b/static/app/views/metrics/utils/index.spec.tsx index 5c13f356807ad4..d68d06008d6a83 100644 --- a/static/app/views/metrics/utils/index.spec.tsx +++ b/static/app/views/metrics/utils/index.spec.tsx @@ -1,4 +1,4 @@ -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import {MetricSeriesFilterUpdateType} from 'sentry/utils/metrics/types'; import {updateQueryWithSeriesFilter} from './index'; diff --git a/static/app/views/metrics/utils/useMetricsIntervalParam.tsx b/static/app/views/metrics/utils/useMetricsIntervalParam.tsx index d7fe6d5d8919b1..c3ce287afef8a9 100644 --- a/static/app/views/metrics/utils/useMetricsIntervalParam.tsx +++ b/static/app/views/metrics/utils/useMetricsIntervalParam.tsx @@ -12,7 +12,7 @@ import { } from 'sentry/components/charts/utils'; import {parseStatsPeriod} from 'sentry/components/organizations/pageFilters/parse'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {parsePeriodToHours} from 'sentry/utils/dates'; import {useUpdateQuery} from 'sentry/utils/metrics'; import {parseMRI} from 'sentry/utils/metrics/mri'; diff --git a/static/app/views/metrics/widgetDetails.tsx b/static/app/views/metrics/widgetDetails.tsx index 822e987edd7932..784c581a4c4515 100644 --- a/static/app/views/metrics/widgetDetails.tsx +++ b/static/app/views/metrics/widgetDetails.tsx @@ -11,7 +11,7 @@ import {TabList, TabPanels, Tabs} from 'sentry/components/tabs'; import {Tooltip} from 'sentry/components/tooltip'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {MRI} from 'sentry/types'; +import type {MRI} from 'sentry/types/metrics'; import {trackAnalytics} from 'sentry/utils/analytics'; import {isCustomMetric} from 'sentry/utils/metrics'; import type { diff --git a/static/app/views/monitors/components/monitorForm.tsx b/static/app/views/monitors/components/monitorForm.tsx index 9d2022e46865c5..d9fd39eb857fed 100644 --- a/static/app/views/monitors/components/monitorForm.tsx +++ b/static/app/views/monitors/components/monitorForm.tsx @@ -21,7 +21,7 @@ import Text from 'sentry/components/text'; import {timezoneOptions} from 'sentry/data/timezones'; import {t, tct, tn} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser'; import slugify from 'sentry/utils/slugify'; import commonTheme from 'sentry/utils/theme'; diff --git a/static/app/views/monitors/components/monitorQuickStartGuide.tsx b/static/app/views/monitors/components/monitorQuickStartGuide.tsx index dbe6c22f0f33e3..3abdd58aaa99ca 100644 --- a/static/app/views/monitors/components/monitorQuickStartGuide.tsx +++ b/static/app/views/monitors/components/monitorQuickStartGuide.tsx @@ -5,7 +5,7 @@ import partition from 'lodash/partition'; import {CompactSelect} from 'sentry/components/compactSelect'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PlatformKey, ProjectKey} from 'sentry/types'; +import type {PlatformKey, ProjectKey} from 'sentry/types/project'; import {useApiQuery} from 'sentry/utils/queryClient'; import useOrganization from 'sentry/utils/useOrganization'; import type {QuickStartProps} from 'sentry/views/monitors/components/quickStartEntries'; diff --git a/static/app/views/monitors/components/timeline/utils/getTimeRangeFromEvent.tsx b/static/app/views/monitors/components/timeline/utils/getTimeRangeFromEvent.tsx index d3fa812531a5b3..ba158bb5c95e75 100644 --- a/static/app/views/monitors/components/timeline/utils/getTimeRangeFromEvent.tsx +++ b/static/app/views/monitors/components/timeline/utils/getTimeRangeFromEvent.tsx @@ -1,6 +1,6 @@ import moment from 'moment'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import type {TimeWindow} from '../types'; diff --git a/static/app/views/organizationStats/index.spec.tsx b/static/app/views/organizationStats/index.spec.tsx index 807b7b74936bb0..cacffef36bc840 100644 --- a/static/app/views/organizationStats/index.spec.tsx +++ b/static/app/views/organizationStats/index.spec.tsx @@ -8,7 +8,7 @@ import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters'; import OrganizationStore from 'sentry/stores/organizationStore'; import PageFiltersStore from 'sentry/stores/pageFiltersStore'; import ProjectsStore from 'sentry/stores/projectsStore'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {OrganizationStats, PAGE_QUERY_PARAMS} from 'sentry/views/organizationStats'; import {ChartDataTransform} from './usageChart'; diff --git a/static/app/views/performance/browser/webVitals/components/pageOverviewSidebar.tsx b/static/app/views/performance/browser/webVitals/components/pageOverviewSidebar.tsx index b559fb415315ba..6dad7cc0391d24 100644 --- a/static/app/views/performance/browser/webVitals/components/pageOverviewSidebar.tsx +++ b/static/app/views/performance/browser/webVitals/components/pageOverviewSidebar.tsx @@ -10,7 +10,7 @@ import ExternalLink from 'sentry/components/links/externalLink'; import QuestionTooltip from 'sentry/components/questionTooltip'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {SeriesDataUnit} from 'sentry/types/echarts'; import {formatAbbreviatedNumber} from 'sentry/utils/formatters'; import {getPeriod} from 'sentry/utils/getPeriod'; diff --git a/static/app/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery.tsx b/static/app/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery.tsx index 927c837f288875..8b90d93cf77945 100644 --- a/static/app/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery.tsx +++ b/static/app/views/performance/browser/webVitals/utils/queries/rawWebVitalsQueries/useProjectRawWebVitalsValuesTimeseriesQuery.tsx @@ -1,5 +1,5 @@ import {getInterval} from 'sentry/components/charts/utils'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {SeriesDataUnit} from 'sentry/types/echarts'; import type {MetaType} from 'sentry/utils/discover/eventView'; import EventView from 'sentry/utils/discover/eventView'; diff --git a/static/app/views/performance/charts/chart.tsx b/static/app/views/performance/charts/chart.tsx index 72eca39a3e2a60..cf6d1858bfb2bb 100644 --- a/static/app/views/performance/charts/chart.tsx +++ b/static/app/views/performance/charts/chart.tsx @@ -6,7 +6,7 @@ import type {AreaChartProps} from 'sentry/components/charts/areaChart'; import {AreaChart} from 'sentry/components/charts/areaChart'; import ChartZoom from 'sentry/components/charts/chartZoom'; import {LineChart} from 'sentry/components/charts/lineChart'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type {Series} from 'sentry/types/echarts'; import { axisLabelFormatter, diff --git a/static/app/views/performance/newTraceDetails/traceApi/useTrace.tsx b/static/app/views/performance/newTraceDetails/traceApi/useTrace.tsx index 3b6dd00e117d7c..7f9b53c1b96d43 100644 --- a/static/app/views/performance/newTraceDetails/traceApi/useTrace.tsx +++ b/static/app/views/performance/newTraceDetails/traceApi/useTrace.tsx @@ -4,7 +4,7 @@ import * as qs from 'query-string'; import type {Client} from 'sentry/api'; import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type { TraceFullDetailed, TraceSplitResults, diff --git a/static/app/views/performance/newTraceDetails/traceApi/useTraceMeta.tsx b/static/app/views/performance/newTraceDetails/traceApi/useTraceMeta.tsx index 42fcb353e7eb52..adfe3a5def1830 100644 --- a/static/app/views/performance/newTraceDetails/traceApi/useTraceMeta.tsx +++ b/static/app/views/performance/newTraceDetails/traceApi/useTraceMeta.tsx @@ -4,7 +4,7 @@ import * as qs from 'query-string'; import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; import {DEFAULT_STATS_PERIOD} from 'sentry/constants'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {TraceMeta} from 'sentry/utils/performance/quickTrace/types'; import {useApiQuery, type UseApiQueryResult} from 'sentry/utils/queryClient'; import {decodeScalar} from 'sentry/utils/queryString'; diff --git a/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx b/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx index a399a53abd13ab..864528fbaa532f 100644 --- a/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx +++ b/static/app/views/performance/traceDetails/TraceDetailsRouting.tsx @@ -3,7 +3,7 @@ import type {LocationDescriptorObject} from 'history'; import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; import {getEventTimestamp} from 'sentry/components/quickTrace/utils'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {useLocation} from 'sentry/utils/useLocation'; import useOrganization from 'sentry/utils/useOrganization'; diff --git a/static/app/views/performance/traces/content.tsx b/static/app/views/performance/traces/content.tsx index c025cb8c1f6c5c..7cbde9f1cbb722 100644 --- a/static/app/views/performance/traces/content.tsx +++ b/static/app/views/performance/traces/content.tsx @@ -21,7 +21,7 @@ import type {SmartSearchBarProps} from 'sentry/components/smartSearchBar'; import {IconChevron} from 'sentry/icons/iconChevron'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {useApiQuery} from 'sentry/utils/queryClient'; import {decodeInteger, decodeScalar} from 'sentry/utils/queryString'; import {useLocation} from 'sentry/utils/useLocation'; diff --git a/static/app/views/performance/traces/fieldRenderers.tsx b/static/app/views/performance/traces/fieldRenderers.tsx index 3ae8e1b3c9fc3f..95b5f927c735ea 100644 --- a/static/app/views/performance/traces/fieldRenderers.tsx +++ b/static/app/views/performance/traces/fieldRenderers.tsx @@ -12,7 +12,7 @@ import PerformanceDuration from 'sentry/components/performanceDuration'; import {Tooltip} from 'sentry/components/tooltip'; import {IconIssues} from 'sentry/icons'; import {t} from 'sentry/locale'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls'; import {getShortEventId} from 'sentry/utils/events'; import toPercent from 'sentry/utils/number/toPercent'; diff --git a/static/app/views/performance/transactionDetails/traceLink.tsx b/static/app/views/performance/transactionDetails/traceLink.tsx index 9a1ddbd3530231..becbf521def178 100644 --- a/static/app/views/performance/transactionDetails/traceLink.tsx +++ b/static/app/views/performance/transactionDetails/traceLink.tsx @@ -4,7 +4,7 @@ import styled from '@emotion/styled'; import Link from 'sentry/components/links/link'; import {generateTraceTarget} from 'sentry/components/quickTrace/utils'; import {tct, tn} from 'sentry/locale'; -import type {Event} from 'sentry/types'; +import type {Event} from 'sentry/types/event'; import {trackAnalytics} from 'sentry/utils/analytics'; import {getShortEventId} from 'sentry/utils/events'; import type {QuickTraceContextChildrenProps} from 'sentry/utils/performance/quickTrace/quickTraceContext'; diff --git a/static/app/views/performance/transactionSummary/transactionAnomalies/anomalyChart.tsx b/static/app/views/performance/transactionSummary/transactionAnomalies/anomalyChart.tsx index 1d1a23a96777cb..c6745110a99619 100644 --- a/static/app/views/performance/transactionSummary/transactionAnomalies/anomalyChart.tsx +++ b/static/app/views/performance/transactionSummary/transactionAnomalies/anomalyChart.tsx @@ -3,7 +3,7 @@ import type {LineChartProps} from 'sentry/components/charts/lineChart'; import {LineChart} from 'sentry/components/charts/lineChart'; import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; import {t} from 'sentry/locale'; -import type {DateString} from 'sentry/types'; +import type {DateString} from 'sentry/types/core'; import type {Series} from 'sentry/types/echarts'; import {getUtcToLocalDateObject} from 'sentry/utils/dates'; import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts'; diff --git a/static/app/views/performance/transactionSummary/transactionTags/constants.tsx b/static/app/views/performance/transactionSummary/transactionTags/constants.tsx index 2fe91507e7b13b..9bed9254db6d62 100644 --- a/static/app/views/performance/transactionSummary/transactionTags/constants.tsx +++ b/static/app/views/performance/transactionSummary/transactionTags/constants.tsx @@ -1,5 +1,5 @@ import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {XAxisOption} from './types'; diff --git a/static/app/views/profiling/landing/profileCharts.tsx b/static/app/views/profiling/landing/profileCharts.tsx index 392205b0dcd5e2..61e305d21cf572 100644 --- a/static/app/views/profiling/landing/profileCharts.tsx +++ b/static/app/views/profiling/landing/profileCharts.tsx @@ -10,7 +10,7 @@ import {HeaderTitle} from 'sentry/components/charts/styles'; import Panel from 'sentry/components/panels/panel'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {Series} from 'sentry/types/echarts'; import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts'; import {aggregateOutputType} from 'sentry/utils/discover/fields'; diff --git a/static/app/views/profiling/landing/profilesChartWidget.tsx b/static/app/views/profiling/landing/profilesChartWidget.tsx index a16e243cdc29cd..e4f28482c6ac1f 100644 --- a/static/app/views/profiling/landing/profilesChartWidget.tsx +++ b/static/app/views/profiling/landing/profilesChartWidget.tsx @@ -5,7 +5,7 @@ import {useTheme} from '@emotion/react'; import {AreaChart} from 'sentry/components/charts/areaChart'; import ChartZoom from 'sentry/components/charts/chartZoom'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {Series} from 'sentry/types/echarts'; import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts'; import {useProfileEventsStats} from 'sentry/utils/profiling/hooks/useProfileEventsStats'; diff --git a/static/app/views/profiling/landing/profilesSummaryChart.tsx b/static/app/views/profiling/landing/profilesSummaryChart.tsx index ac5f70c0dd7d6d..bb352ad0468d00 100644 --- a/static/app/views/profiling/landing/profilesSummaryChart.tsx +++ b/static/app/views/profiling/landing/profilesSummaryChart.tsx @@ -7,7 +7,7 @@ import {AreaChart} from 'sentry/components/charts/areaChart'; import ChartZoom from 'sentry/components/charts/chartZoom'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {Series} from 'sentry/types/echarts'; import {axisLabelFormatter, tooltipFormatter} from 'sentry/utils/discover/charts'; import {aggregateOutputType} from 'sentry/utils/discover/fields'; diff --git a/static/app/views/profiling/utils.tsx b/static/app/views/profiling/utils.tsx index 5da0d04957a9cc..38dda3800ff7a0 100644 --- a/static/app/views/profiling/utils.tsx +++ b/static/app/views/profiling/utils.tsx @@ -3,7 +3,7 @@ import type {Location} from 'history'; import type {GridColumnOrder} from 'sentry/components/gridEditable'; import SortLink from 'sentry/components/gridEditable/sortLink'; import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; import {defined} from 'sentry/utils'; import {decodeScalar} from 'sentry/utils/queryString'; diff --git a/static/app/views/projectDetail/charts/projectBaseEventsChart.tsx b/static/app/views/projectDetail/charts/projectBaseEventsChart.tsx index 542cf977e07128..99822f923d8597 100644 --- a/static/app/views/projectDetail/charts/projectBaseEventsChart.tsx +++ b/static/app/views/projectDetail/charts/projectBaseEventsChart.tsx @@ -9,7 +9,7 @@ import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilte import {isSelectionEqual} from 'sentry/components/organizations/pageFilters/utils'; import QuestionTooltip from 'sentry/components/questionTooltip'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {axisLabelFormatter} from 'sentry/utils/discover/charts'; import {aggregateOutputType} from 'sentry/utils/discover/fields'; import {DiscoverDatasets} from 'sentry/utils/discover/types'; diff --git a/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.spec.tsx b/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.spec.tsx index 9cebc9861750bb..d719bfa050ddb8 100644 --- a/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.spec.tsx +++ b/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.spec.tsx @@ -1,7 +1,7 @@ import {initializeOrg} from 'sentry-test/initializeOrg'; import {render, screen, waitFor} from 'sentry-test/reactTestingLibrary'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {ProjectAnrScoreCard} from 'sentry/views/projectDetail/projectScoreCards/projectAnrScoreCard'; describe('ProjectDetail > ProjectAnr', function () { diff --git a/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.tsx b/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.tsx index 5ce1df4066083a..c422bd4c04e46a 100644 --- a/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.tsx +++ b/static/app/views/projectDetail/projectScoreCards/projectAnrScoreCard.tsx @@ -12,7 +12,7 @@ import {parseStatsPeriod} from 'sentry/components/timeRangeSelector/utils'; import {URL_PARAM} from 'sentry/constants/pageFilters'; import {IconArrow} from 'sentry/icons/iconArrow'; import {t} from 'sentry/locale'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import type {Organization, SessionApiResponse} from 'sentry/types/organization'; import {trackAnalytics} from 'sentry/utils/analytics'; import {formatAbbreviatedNumber, formatPercentage} from 'sentry/utils/formatters'; diff --git a/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx b/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx index 36153a67977a64..d76e9a53eb5f10 100644 --- a/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx +++ b/static/app/views/releases/detail/commitsAndFiles/repositorySwitcher.tsx @@ -2,7 +2,7 @@ import styled from '@emotion/styled'; import {CompactSelect} from 'sentry/components/compactSelect'; import {t} from 'sentry/locale'; -import type {Repository} from 'sentry/types'; +import type {Repository} from 'sentry/types/integrations'; import {useLocation} from 'sentry/utils/useLocation'; import useRouter from 'sentry/utils/useRouter'; diff --git a/static/app/views/releases/list/releaseCard/releaseCardStatsPeriod.tsx b/static/app/views/releases/list/releaseCard/releaseCardStatsPeriod.tsx index c5739e6850b7e6..ab6d4598fe0e6b 100644 --- a/static/app/views/releases/list/releaseCard/releaseCardStatsPeriod.tsx +++ b/static/app/views/releases/list/releaseCard/releaseCardStatsPeriod.tsx @@ -4,8 +4,8 @@ import type {Location} from 'history'; import Link from 'sentry/components/links/link'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {PageFilters} from 'sentry/types'; import {HealthStatsPeriodOption} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import withPageFilters from 'sentry/utils/withPageFilters'; type Props = { diff --git a/static/app/views/settings/account/notifications/fields.tsx b/static/app/views/settings/account/notifications/fields.tsx index b78bb56b7b5670..7ca27c1edd6d7b 100644 --- a/static/app/views/settings/account/notifications/fields.tsx +++ b/static/app/views/settings/account/notifications/fields.tsx @@ -1,5 +1,5 @@ import {t} from 'sentry/locale'; -import type {SelectValue} from 'sentry/types'; +import type {SelectValue} from 'sentry/types/core'; export type FineTuneField = { description: string; diff --git a/static/app/views/settings/organizationRepositories/index.tsx b/static/app/views/settings/organizationRepositories/index.tsx index 44bfdfe376a60f..b23cdf9710396b 100644 --- a/static/app/views/settings/organizationRepositories/index.tsx +++ b/static/app/views/settings/organizationRepositories/index.tsx @@ -5,7 +5,7 @@ import LoadingIndicator from 'sentry/components/loadingIndicator'; import Pagination from 'sentry/components/pagination'; import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle'; import {t} from 'sentry/locale'; -import type {Repository} from 'sentry/types'; +import type {Repository} from 'sentry/types/integrations'; import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient'; import routeTitleGen from 'sentry/utils/routeTitle'; import {useLocation} from 'sentry/utils/useLocation'; diff --git a/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx b/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx index 296939ab603859..5060f24585ec54 100644 --- a/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx +++ b/static/app/views/settings/organizationSecurityAndPrivacy/index.tsx @@ -7,7 +7,8 @@ import JsonForm from 'sentry/components/forms/jsonForm'; import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle'; import organizationSecurityAndPrivacyGroups from 'sentry/data/forms/organizationSecurityAndPrivacyGroups'; import {t} from 'sentry/locale'; -import type {AuthProvider, Organization} from 'sentry/types'; +import type {AuthProvider} from 'sentry/types/auth'; +import type {Organization} from 'sentry/types/organization'; import useApi from 'sentry/utils/useApi'; import useOrganization from 'sentry/utils/useOrganization'; import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader'; diff --git a/static/app/views/settings/organizationTeams/allTeamsList.tsx b/static/app/views/settings/organizationTeams/allTeamsList.tsx index d15caee4d2dbd7..123a6583aecf00 100644 --- a/static/app/views/settings/organizationTeams/allTeamsList.tsx +++ b/static/app/views/settings/organizationTeams/allTeamsList.tsx @@ -5,7 +5,7 @@ import {openCreateTeamModal} from 'sentry/actionCreators/modal'; import {Button} from 'sentry/components/button'; import EmptyMessage from 'sentry/components/emptyMessage'; import {t, tct} from 'sentry/locale'; -import type {Organization, Team} from 'sentry/types'; +import type {Organization, Team} from 'sentry/types/organization'; import TextBlock from 'sentry/views/settings/components/text/textBlock'; import AllTeamsRow from './allTeamsRow'; diff --git a/static/app/views/settings/organizationTeams/allTeamsRow.tsx b/static/app/views/settings/organizationTeams/allTeamsRow.tsx index 5761076f2983b0..8b6a88a2c7f7b6 100644 --- a/static/app/views/settings/organizationTeams/allTeamsRow.tsx +++ b/static/app/views/settings/organizationTeams/allTeamsRow.tsx @@ -12,7 +12,7 @@ import PanelItem from 'sentry/components/panels/panelItem'; import {t, tct, tn} from 'sentry/locale'; import TeamStore from 'sentry/stores/teamStore'; import {space} from 'sentry/styles/space'; -import type {Organization, Team} from 'sentry/types'; +import type {Organization, Team} from 'sentry/types/organization'; import withApi from 'sentry/utils/withApi'; import {getButtonHelpText} from 'sentry/views/settings/organizationTeams/utils'; diff --git a/static/app/views/settings/organizationTeams/index.tsx b/static/app/views/settings/organizationTeams/index.tsx index 34eb6fb337faad..4125b0b01b9b64 100644 --- a/static/app/views/settings/organizationTeams/index.tsx +++ b/static/app/views/settings/organizationTeams/index.tsx @@ -3,7 +3,7 @@ import type {RouteComponentProps} from 'react-router'; import {loadStats} from 'sentry/actionCreators/projects'; import type {Client} from 'sentry/api'; import TeamStore from 'sentry/stores/teamStore'; -import type {AccessRequest, Organization, Team} from 'sentry/types'; +import type {AccessRequest, Organization, Team} from 'sentry/types/organization'; import withApi from 'sentry/utils/withApi'; import withOrganization from 'sentry/utils/withOrganization'; import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView'; diff --git a/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx b/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx index 7eb045d3a1cfad..8ba876176a3e6f 100644 --- a/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx +++ b/static/app/views/settings/organizationTeams/organizationAccessRequests.tsx @@ -10,7 +10,7 @@ import PanelHeader from 'sentry/components/panels/panelHeader'; import PanelItem from 'sentry/components/panels/panelItem'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {AccessRequest} from 'sentry/types'; +import type {AccessRequest} from 'sentry/types/organization'; import withApi from 'sentry/utils/withApi'; type Props = { diff --git a/static/app/views/settings/organizationTeams/organizationTeams.tsx b/static/app/views/settings/organizationTeams/organizationTeams.tsx index defb6ec527d905..b0747c93ace3bf 100644 --- a/static/app/views/settings/organizationTeams/organizationTeams.tsx +++ b/static/app/views/settings/organizationTeams/organizationTeams.tsx @@ -17,7 +17,7 @@ import {DEFAULT_DEBOUNCE_DURATION} from 'sentry/constants'; import {IconAdd} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {AccessRequest, Organization} from 'sentry/types'; +import type {AccessRequest, Organization} from 'sentry/types/organization'; import {useTeams} from 'sentry/utils/useTeams'; import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader'; import {RoleOverwritePanelAlert} from 'sentry/views/settings/organizationTeams/roleOverwriteWarning'; diff --git a/static/app/views/settings/organizationTeams/roleOverwriteWarning.tsx b/static/app/views/settings/organizationTeams/roleOverwriteWarning.tsx index 80cc8e3cf2367a..fbaaf774287904 100644 --- a/static/app/views/settings/organizationTeams/roleOverwriteWarning.tsx +++ b/static/app/views/settings/organizationTeams/roleOverwriteWarning.tsx @@ -2,7 +2,7 @@ import PanelAlert from 'sentry/components/panels/panelAlert'; import {Tooltip} from 'sentry/components/tooltip'; import {IconInfo} from 'sentry/icons'; import {tct} from 'sentry/locale'; -import type {OrgRole, TeamRole} from 'sentry/types'; +import type {OrgRole, TeamRole} from 'sentry/types/organization'; type Props = { orgRole: OrgRole['id'] | undefined; diff --git a/static/app/views/settings/organizationTeams/teamMembers.tsx b/static/app/views/settings/organizationTeams/teamMembers.tsx index da0d15c27d2bd9..028ad12e0afbbf 100644 --- a/static/app/views/settings/organizationTeams/teamMembers.tsx +++ b/static/app/views/settings/organizationTeams/teamMembers.tsx @@ -26,7 +26,8 @@ import {TeamRoleColumnLabel} from 'sentry/components/teamRoleUtils'; import {IconUser} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Config, Member, Organization, Team, TeamMember} from 'sentry/types'; +import type {Member, Organization, Team, TeamMember} from 'sentry/types/organization'; +import type {Config} from 'sentry/types/system'; import withApi from 'sentry/utils/withApi'; import withConfig from 'sentry/utils/withConfig'; import withOrganization from 'sentry/utils/withOrganization'; diff --git a/static/app/views/settings/organizationTeams/teamMembersRow.tsx b/static/app/views/settings/organizationTeams/teamMembersRow.tsx index 80550a59c432d8..f017a98a829b15 100644 --- a/static/app/views/settings/organizationTeams/teamMembersRow.tsx +++ b/static/app/views/settings/organizationTeams/teamMembersRow.tsx @@ -7,7 +7,8 @@ import TeamRoleSelect from 'sentry/components/teamRoleSelect'; import {IconSubtract} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {Member, Organization, Team, TeamMember, User} from 'sentry/types'; +import type {Member, Organization, Team, TeamMember} from 'sentry/types/organization'; +import type {User} from 'sentry/types/user'; import {getButtonHelpText} from 'sentry/views/settings/organizationTeams/utils'; interface Props { diff --git a/static/app/views/settings/organizationTeams/teamNotifications.tsx b/static/app/views/settings/organizationTeams/teamNotifications.tsx index af4a285f8885ed..1f77f6d11179c3 100644 --- a/static/app/views/settings/organizationTeams/teamNotifications.tsx +++ b/static/app/views/settings/organizationTeams/teamNotifications.tsx @@ -17,7 +17,8 @@ import {Tooltip} from 'sentry/components/tooltip'; import {IconDelete} from 'sentry/icons'; import {t, tct} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {ExternalTeam, Integration, Organization, Team} from 'sentry/types'; +import type {ExternalTeam, Integration} from 'sentry/types/integrations'; +import type {Organization, Team} from 'sentry/types/organization'; import {toTitleCase} from 'sentry/utils'; import withOrganization from 'sentry/utils/withOrganization'; import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView'; diff --git a/static/app/views/settings/organizationTeams/teamProjects.tsx b/static/app/views/settings/organizationTeams/teamProjects.tsx index e3b26cd71162be..0ad1ff07f9925e 100644 --- a/static/app/views/settings/organizationTeams/teamProjects.tsx +++ b/static/app/views/settings/organizationTeams/teamProjects.tsx @@ -20,7 +20,8 @@ import {IconFlag, IconSubtract} from 'sentry/icons'; import {t} from 'sentry/locale'; import ProjectsStore from 'sentry/stores/projectsStore'; import {space} from 'sentry/styles/space'; -import type {Project, Team} from 'sentry/types'; +import type {Team} from 'sentry/types/organization'; +import type {Project} from 'sentry/types/project'; import {sortProjects} from 'sentry/utils'; import {useApiQuery} from 'sentry/utils/queryClient'; import useApi from 'sentry/utils/useApi'; diff --git a/static/app/views/settings/project/projectFilters/groupTombstones.tsx b/static/app/views/settings/project/projectFilters/groupTombstones.tsx index bef08f6a7a045e..06d34da3d6492e 100644 --- a/static/app/views/settings/project/projectFilters/groupTombstones.tsx +++ b/static/app/views/settings/project/projectFilters/groupTombstones.tsx @@ -17,7 +17,8 @@ import PanelItem from 'sentry/components/panels/panelItem'; import {IconDelete} from 'sentry/icons'; import {t} from 'sentry/locale'; import {space} from 'sentry/styles/space'; -import type {GroupTombstone, Project} from 'sentry/types'; +import type {GroupTombstone} from 'sentry/types/group'; +import type {Project} from 'sentry/types/project'; import {useApiQuery} from 'sentry/utils/queryClient'; import useApi from 'sentry/utils/useApi'; import {useLocation} from 'sentry/utils/useLocation'; diff --git a/static/app/views/starfish/queries/getSeriesEventView.tsx b/static/app/views/starfish/queries/getSeriesEventView.tsx index d93955028c4354..f626335556c1f8 100644 --- a/static/app/views/starfish/queries/getSeriesEventView.tsx +++ b/static/app/views/starfish/queries/getSeriesEventView.tsx @@ -1,6 +1,6 @@ import sortBy from 'lodash/sortBy'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {intervalToMilliseconds} from 'sentry/utils/dates'; import EventView from 'sentry/utils/discover/eventView'; import {parseFunction} from 'sentry/utils/discover/fields'; diff --git a/static/app/views/starfish/queries/useIndexedSpans.tsx b/static/app/views/starfish/queries/useIndexedSpans.tsx index 891b34f1ed663f..c16f6d90b11253 100644 --- a/static/app/views/starfish/queries/useIndexedSpans.tsx +++ b/static/app/views/starfish/queries/useIndexedSpans.tsx @@ -1,4 +1,4 @@ -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import EventView from 'sentry/utils/discover/eventView'; import type {Sort} from 'sentry/utils/discover/fields'; import {DiscoverDatasets} from 'sentry/utils/discover/types'; diff --git a/static/app/views/starfish/queries/useSpanMetrics.tsx b/static/app/views/starfish/queries/useSpanMetrics.tsx index 0784d3e6bfcc4c..e349eab91cd83c 100644 --- a/static/app/views/starfish/queries/useSpanMetrics.tsx +++ b/static/app/views/starfish/queries/useSpanMetrics.tsx @@ -1,4 +1,4 @@ -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import EventView from 'sentry/utils/discover/eventView'; import type {Sort} from 'sentry/utils/discover/fields'; import {DiscoverDatasets} from 'sentry/utils/discover/types'; diff --git a/static/app/views/starfish/utils/getDateConditions.tsx b/static/app/views/starfish/utils/getDateConditions.tsx index e5679abf9cc4cf..264e9e58c6a2db 100644 --- a/static/app/views/starfish/utils/getDateConditions.tsx +++ b/static/app/views/starfish/utils/getDateConditions.tsx @@ -1,5 +1,5 @@ import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; import {getDateFilters} from 'sentry/views/starfish/utils/getDateFilters'; export const getDateConditions = ( diff --git a/static/app/views/starfish/utils/getDateFilters.tsx b/static/app/views/starfish/utils/getDateFilters.tsx index 48632e5030162f..fa08f8d4eb3b0b 100644 --- a/static/app/views/starfish/utils/getDateFilters.tsx +++ b/static/app/views/starfish/utils/getDateFilters.tsx @@ -1,6 +1,6 @@ import moment from 'moment'; -import type {PageFilters} from 'sentry/types'; +import type {PageFilters} from 'sentry/types/core'; const PERIOD_REGEX = /^(\d+)([h,d])$/;
8c3c7fb5e4a48dca753beabfc6531fa5e810fb1a
2022-04-28 05:03:56
Ryan Albrecht
feat(replay): Redesign of the details page (#33994)
false
Redesign of the details page (#33994)
feat
diff --git a/static/app/components/replays/breadcrumbs/replayBreadcrumbOverview.tsx b/static/app/components/replays/breadcrumbs/replayBreadcrumbOverview.tsx index 715aa60e11cd32..fde3efeb813f18 100644 --- a/static/app/components/replays/breadcrumbs/replayBreadcrumbOverview.tsx +++ b/static/app/components/replays/breadcrumbs/replayBreadcrumbOverview.tsx @@ -11,18 +11,17 @@ import {countColumns, formatTime, getCrumbsByColumn} from '../utils'; const EVENT_STICK_MARKER_WIDTH = 2; interface Props { - data: { - values: Array<RawCrumb>; - }; + crumbs: Array<RawCrumb>; + className?: string; } type LineStyle = 'dotted' | 'solid' | 'none'; -function ReplayBreadcrumbOverview({data}: Props) { - const transformedCrumbs = transformCrumbs(data.values); +function ReplayBreadcrumbOverview({crumbs, className}: Props) { + const transformedCrumbs = transformCrumbs(crumbs); return ( - <StackedContent> + <StackedContent className={className}> {({width}) => ( <React.Fragment> <Ticks diff --git a/static/app/components/replays/stackedContent.tsx b/static/app/components/replays/stackedContent.tsx index 504a9257185489..ea049d3f151d5d 100644 --- a/static/app/components/replays/stackedContent.tsx +++ b/static/app/components/replays/stackedContent.tsx @@ -6,6 +6,7 @@ type Dimensions = {height: number; width: number}; type Props = { children: (props: Dimensions) => React.ReactElement | null; + className?: string; }; /** @@ -16,7 +17,7 @@ type Props = { * Injest the width/height of the container, so children can adjust and expand * to fill the whole area. */ -function StackedContent({children}: Props) { +function StackedContent({children, className}: Props) { const el = useRef<HTMLDivElement>(null); const [dimensions, setDimensions] = useState({height: 0, width: 0}); @@ -30,7 +31,11 @@ function StackedContent({children}: Props) { useResizeObserver({ref: el, onResize}); - return <Stack ref={el}>{children(dimensions)}</Stack>; + return ( + <Stack className={className} ref={el}> + {children(dimensions)} + </Stack> + ); } const Stack = styled('div')` diff --git a/static/app/views/replays/detail/detailLayout.tsx b/static/app/views/replays/detail/detailLayout.tsx new file mode 100644 index 00000000000000..a76e9bc6a5c9c1 --- /dev/null +++ b/static/app/views/replays/detail/detailLayout.tsx @@ -0,0 +1,80 @@ +import React from 'react'; +import styled from '@emotion/styled'; + +import Breadcrumbs from 'sentry/components/breadcrumbs'; +import EventOrGroupTitle from 'sentry/components/eventOrGroupTitle'; +import EventMessage from 'sentry/components/events/eventMessage'; +import FeatureBadge from 'sentry/components/featureBadge'; +import * as Layout from 'sentry/components/layouts/thirds'; +import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle'; +import {t} from 'sentry/locale'; +import space from 'sentry/styles/space'; +import {Event} from 'sentry/types/event'; +import {getMessage} from 'sentry/utils/events'; + +type Props = { + children: React.ReactNode; + event: Event | undefined; + orgId: string; +}; + +function DetailLayout({children, event, orgId}: Props) { + const title = event ? `${event.id} - Replays - ${orgId}` : `Replays - ${orgId}`; + + return ( + <SentryDocumentTitle title={title}> + <React.Fragment> + <Layout.Header> + <Layout.HeaderContent> + <Breadcrumbs + crumbs={[ + { + to: `/organizations/${orgId}/replays/`, + label: t('Replays'), + }, + {label: t('Replay Details')}, // TODO(replay): put replay ID or something here + ]} + /> + <EventHeader event={event} /> + </Layout.HeaderContent> + </Layout.Header> + {children} + </React.Fragment> + </SentryDocumentTitle> + ); +} + +function EventHeader({event}: Pick<Props, 'event'>) { + if (!event) { + return null; + } + const message = getMessage(event); + return ( + <EventHeaderContainer data-test-id="event-header"> + <TitleWrapper> + <EventOrGroupTitle data={event} /> + <FeatureBadge type="alpha" /> + </TitleWrapper> + {message && ( + <MessageWrapper> + <EventMessage message={message} /> + </MessageWrapper> + )} + </EventHeaderContainer> + ); +} + +const EventHeaderContainer = styled('div')` + max-width: ${p => p.theme.breakpoints[0]}; +`; + +const TitleWrapper = styled('div')` + font-size: ${p => p.theme.headerFontSize}; + margin-top: ${space(3)}; +`; + +const MessageWrapper = styled('div')` + margin-top: ${space(1)}; +`; + +export default DetailLayout; diff --git a/static/app/views/replays/detail/focusArea.tsx b/static/app/views/replays/detail/focusArea.tsx new file mode 100644 index 00000000000000..43df0476b83ed9 --- /dev/null +++ b/static/app/views/replays/detail/focusArea.tsx @@ -0,0 +1,68 @@ +import React, {useState} from 'react'; + +import EventEntry from 'sentry/components/events/eventEntry'; +import TagsTable from 'sentry/components/tagsTable'; +import {Event} from 'sentry/types/event'; +import useOrganization from 'sentry/utils/useOrganization'; +import {useRouteContext} from 'sentry/utils/useRouteContext'; + +import {TabBarId} from '../types'; + +import FocusButtons from './focusButtons'; + +type Props = { + event: Event; + eventWithSpans: Event | undefined; +}; + +function FocusArea(props: Props) { + const [active, setActive] = useState<TabBarId>('performance'); + + return ( + <React.Fragment> + <FocusButtons active={active} setActive={setActive} /> + <ActiveTab active={active} {...props} /> + </React.Fragment> + ); +} + +function ActiveTab({active, event, eventWithSpans}: Props & {active: TabBarId}) { + const {routes, router} = useRouteContext(); + const organization = useOrganization(); + + switch (active) { + case 'console': + return <div id="console">TODO: Add a console view</div>; + case 'performance': + return eventWithSpans ? ( + <div id="performance"> + <EventEntry + key={`${eventWithSpans.id}`} + projectSlug={getProjectSlug(eventWithSpans)} + // group={group} + organization={organization} + event={eventWithSpans} + entry={eventWithSpans.entries[0]} + route={routes[routes.length - 1]} + router={router} + /> + </div> + ) : null; + case 'errors': + return <div id="errors">TODO: Add an errors view</div>; + case 'tags': + return ( + <div id="tags"> + <TagsTable generateUrl={() => ''} event={event} query="" /> + </div> + ); + default: + return null; + } +} + +function getProjectSlug(event: Event) { + return event.projectSlug || event['project.name']; // seems janky +} + +export default FocusArea; diff --git a/static/app/views/replays/detail/focusButtons.tsx b/static/app/views/replays/detail/focusButtons.tsx new file mode 100644 index 00000000000000..733edab2deb459 --- /dev/null +++ b/static/app/views/replays/detail/focusButtons.tsx @@ -0,0 +1,44 @@ +import React from 'react'; + +import NavTabs from 'sentry/components/navTabs'; +import {t} from 'sentry/locale'; + +import {TabBarId} from '../types'; + +type Props = { + active: TabBarId; + setActive: (id: TabBarId) => void; +}; + +function FocusButtons({active, setActive}: Props) { + const select = (barId: TabBarId) => () => { + setActive(barId); + }; + + return ( + <NavTabs underlined> + <li className={active === 'console' ? 'active' : ''}> + <a href="#console" onClick={select('console')}> + {t('Console')} + </a> + </li> + <li className={active === 'performance' ? 'active' : ''}> + <a href="#performance" onClick={select('performance')}> + {t('Performance')} + </a> + </li> + <li className={active === 'errors' ? 'active' : ''}> + <a href="#errors" onClick={select('errors')}> + {t('Errors')} + </a> + </li> + <li className={active === 'tags' ? 'active' : ''}> + <a href="#tags" onClick={select('tags')}> + {t('Tags')} + </a> + </li> + </NavTabs> + ); +} + +export default FocusButtons; diff --git a/static/app/views/replays/detail/userActionsNavigator.tsx b/static/app/views/replays/detail/userActionsNavigator.tsx new file mode 100644 index 00000000000000..2cc053c510e671 --- /dev/null +++ b/static/app/views/replays/detail/userActionsNavigator.tsx @@ -0,0 +1,42 @@ +import React from 'react'; + +import EventEntry from 'sentry/components/events/eventEntry'; +import {Entry, Event} from 'sentry/types/event'; +import useOrganization from 'sentry/utils/useOrganization'; +import {useRouteContext} from 'sentry/utils/useRouteContext'; + +type Props = { + entry: Entry | undefined; + event: Event | undefined; +}; + +function UserActionsNavigator({event, entry}: Props) { + // TODO(replay): New User Actions widget replaces this breadcrumb view + + const {routes, router} = useRouteContext(); + const organization = useOrganization(); + + if (!entry || !event) { + return null; + } + + const projectSlug = getProjectSlug(event); + + return ( + <EventEntry + projectSlug={projectSlug} + // group={group} + organization={organization} + event={event} + entry={entry} + route={routes[routes.length - 1]} + router={router} + /> + ); +} + +function getProjectSlug(event: Event) { + return event.projectSlug || event['project.name']; // seems janky +} + +export default UserActionsNavigator; diff --git a/static/app/views/replays/details.tsx b/static/app/views/replays/details.tsx index 1c65ae1151e298..f2eb627734ca5d 100644 --- a/static/app/views/replays/details.tsx +++ b/static/app/views/replays/details.tsx @@ -1,14 +1,8 @@ import React from 'react'; -import {RouteComponentProps} from 'react-router'; import styled from '@emotion/styled'; -import Breadcrumbs from 'sentry/components/breadcrumbs'; import DetailedError from 'sentry/components/errors/detailedError'; import NotFound from 'sentry/components/errors/notFound'; -import EventOrGroupTitle from 'sentry/components/eventOrGroupTitle'; -import EventEntry from 'sentry/components/events/eventEntry'; -import EventMessage from 'sentry/components/events/eventMessage'; -import FeatureBadge from 'sentry/components/featureBadge'; import * as Layout from 'sentry/components/layouts/thirds'; import LoadingIndicator from 'sentry/components/loadingIndicator'; import ReplayBreadcrumbOverview from 'sentry/components/replays/breadcrumbs/replayBreadcrumbOverview'; @@ -16,145 +10,59 @@ import {Provider as ReplayContextProvider} from 'sentry/components/replays/repla import ReplayController from 'sentry/components/replays/replayController'; import ReplayPlayer from 'sentry/components/replays/replayPlayer'; import useFullscreen from 'sentry/components/replays/useFullscreen'; -import TagsTable from 'sentry/components/tagsTable'; import {t} from 'sentry/locale'; import {PageContent} from 'sentry/styles/organization'; import space from 'sentry/styles/space'; -import {Organization} from 'sentry/types'; -import {Event} from 'sentry/types/event'; -import {getMessage} from 'sentry/utils/events'; -import withOrganization from 'sentry/utils/withOrganization'; -import AsyncView from 'sentry/views/asyncView'; +import {useRouteContext} from 'sentry/utils/useRouteContext'; +import DetailLayout from './detail/detailLayout'; +import FocusArea from './detail/focusArea'; +import UserActionsNavigator from './detail/userActionsNavigator'; import useReplayEvent from './utils/useReplayEvent'; -type Props = AsyncView['props'] & - RouteComponentProps< - { - eventSlug: string; - orgId: string; - }, - {} - > & {organization: Organization}; - -type ReplayLoaderProps = { - eventSlug: string; - location: Props['location']; - orgId: string; - organization: Organization; - route: Props['route']; - router: Props['router']; -}; - -type State = AsyncView['state']; - -const EventHeader = ({event}: {event: Event}) => { - const message = getMessage(event); - return ( - <EventHeaderContainer data-test-id="event-header"> - <TitleWrapper> - <EventOrGroupTitle data={event} /> <FeatureBadge type="alpha" /> - </TitleWrapper> - {message && ( - <MessageWrapper> - <EventMessage message={message} /> - </MessageWrapper> - )} - </EventHeaderContainer> - ); -}; - -class ReplayDetails extends AsyncView<Props, State> { - state: State = { - loading: true, - reloading: false, - error: false, - errors: {}, - }; - - getTitle() { - if (this.state.event) { - return `${this.state.event.id} - Replays - ${this.props.params.orgId}`; - } - return `Replays - ${this.props.params.orgId}`; - } - - renderLoading() { - return <PageContent>{super.renderLoading()}</PageContent>; - } - - renderBody() { - const { - location, - router, - route, - organization, - params: {eventSlug, orgId}, - } = this.props; - return ( - <ReplayLoader - eventSlug={eventSlug} - location={location} - orgId={orgId} - organization={organization} - router={router} - route={route} - /> - ); - } -} - -function getProjectSlug(event: Event) { - return event.projectSlug || event['project.name']; // seems janky -} - -// TODO(replay): investigate the `:fullscreen` CSS selector -// https://caniuse.com/?search=%3Afullscreen -const FullscreenWrapper = styled('div')<{isFullscreen: boolean}>` - ${p => - p.isFullscreen - ? ` - display: grid; - grid-template-rows: auto max-content; - background: ${p.theme.gray500};` - : ''} -`; +function ReplayDetails() { + const { + location, + params: {eventSlug, orgId}, + } = useRouteContext(); -function ReplayLoader(props: ReplayLoaderProps) { - const orgSlug = props.orgId; - const {ref: fullscreenRef, isFullscreen, toggle: toggleFullscreen} = useFullscreen(); const { - fetchError, - fetching, - onRetry, breadcrumbEntry, event, - replayEvents, - rrwebEvents, mergedReplayEvent, - } = useReplayEvent(props); - - /* eslint-disable-next-line no-console */ - console.log({ fetchError, fetching, onRetry, - event, - replayEvents, rrwebEvents, - mergedReplayEvent, + } = useReplayEvent({ + eventSlug, + location, + orgId, }); - const renderMain = () => { - if (fetching) { - return <LoadingIndicator />; - } - if (!event) { - return <NotFound />; - } + const {ref: fullscreenRef, isFullscreen, toggle: toggleFullscreen} = useFullscreen(); - if (!rrwebEvents || rrwebEvents.length < 2) { - return ( + if (fetching) { + return ( + <DetailLayout event={event} orgId={orgId}> + <LoadingIndicator /> + </DetailLayout> + ); + } + if (!event) { + // TODO(replay): Give the user more details when errors happen + console.log({fetching, fetchError}); // eslint-disable-line no-console + return ( + <DetailLayout event={event} orgId={orgId}> + <PageContent> + <NotFound /> + </PageContent> + </DetailLayout> + ); + } + if (!rrwebEvents || rrwebEvents.length < 2) { + return ( + <DetailLayout event={event} orgId={orgId}> <DetailedError onRetry={onRetry} hideSupportLinks @@ -170,95 +78,44 @@ function ReplayLoader(props: ReplayLoaderProps) { </React.Fragment> } /> - ); - } + </DetailLayout> + ); + } - return ( - <React.Fragment> - <ReplayContextProvider events={rrwebEvents}> - <FullscreenWrapper isFullscreen={isFullscreen} ref={fullscreenRef}> + return ( + <DetailLayout event={event} orgId={orgId}> + <ReplayContextProvider events={rrwebEvents}> + <Layout.Body> + <ReplayLayout ref={fullscreenRef}> {/* In fullscreen we need to consider the max-height that the player is able to full up, on a page that scrolls we only consider the max-width. */} <ReplayPlayer fixedHeight={isFullscreen} /> <ReplayController toggleFullscreen={toggleFullscreen} /> - {breadcrumbEntry && <ReplayBreadcrumbOverview data={breadcrumbEntry.data} />} - </FullscreenWrapper> - </ReplayContextProvider> - - {breadcrumbEntry && ( - <EventEntry - projectSlug={getProjectSlug(event)} - // group={group} - organization={props.organization} - event={event} - entry={breadcrumbEntry} - route={props.route} - router={props.router} - /> - )} - - {mergedReplayEvent && ( - <EventEntry - key={`${mergedReplayEvent.id}`} - projectSlug={getProjectSlug(mergedReplayEvent)} - // group={group} - organization={props.organization} - event={mergedReplayEvent} - entry={mergedReplayEvent.entries[0]} - route={props.route} - router={props.router} - /> - )} - </React.Fragment> - ); - }; - - const renderSide = () => { - if (event) { - return <TagsTable generateUrl={() => ''} event={event} query="" />; - } - return null; - }; - - return ( - <NoPaddingContent> - <Layout.Header> - <Layout.HeaderContent> - <Breadcrumbs - crumbs={[ - { - to: `/organizations/${orgSlug}/replays/`, - label: t('Replays'), - }, - {label: t('Replay Details')}, // TODO(replay): put replay ID or something here - ]} - /> - {event ? <EventHeader event={event} /> : null} - </Layout.HeaderContent> - </Layout.Header> - <Layout.Body> - <Layout.Main>{renderMain()}</Layout.Main> - <Layout.Side>{renderSide()}</Layout.Side> - </Layout.Body> - </NoPaddingContent> + </ReplayLayout> + <Layout.Side> + <UserActionsNavigator event={event} entry={breadcrumbEntry} /> + </Layout.Side> + <Layout.Main fullWidth> + <BreadcrumbTimeline crumbs={breadcrumbEntry?.data.values || []} /> + <FocusArea event={event} eventWithSpans={mergedReplayEvent} /> + </Layout.Main> + </Layout.Body> + </ReplayContextProvider> + </DetailLayout> ); } -const EventHeaderContainer = styled('div')` - max-width: ${p => p.theme.breakpoints[0]}; -`; - -const TitleWrapper = styled('div')` - font-size: ${p => p.theme.headerFontSize}; - margin-top: 20px; -`; - -const MessageWrapper = styled('div')` - margin-top: ${space(1)}; +const ReplayLayout = styled(Layout.Main)` + :fullscreen { + display: grid; + grid-template-rows: auto max-content; + background: ${p => p.theme.gray500}; + } `; -const NoPaddingContent = styled(PageContent)` - padding: 0; +const BreadcrumbTimeline = styled(ReplayBreadcrumbOverview)` + max-height: 5em; + margin-bottom: ${space(2)}; `; -export default withOrganization(ReplayDetails); +export default ReplayDetails; diff --git a/static/app/views/replays/types.tsx b/static/app/views/replays/types.tsx index 0955aa42dd8e7a..27342db737263a 100644 --- a/static/app/views/replays/types.tsx +++ b/static/app/views/replays/types.tsx @@ -6,3 +6,5 @@ export type Replay = { url: string; 'user.display': string; }; + +export type TabBarId = 'console' | 'performance' | 'errors' | 'tags';
f325d54b5e0a06be52edef85e6e0781191b0984a
2020-11-19 06:22:09
Billy Vong
build(ci): Add/fix webpack instrumentation for GHA (#22034)
false
Add/fix webpack instrumentation for GHA (#22034)
build
diff --git a/.github/workflows/acceptance-py3.6.yml b/.github/workflows/acceptance-py3.6.yml index 676fee1cda44aa..8c1bfefd8ebf33 100644 --- a/.github/workflows/acceptance-py3.6.yml +++ b/.github/workflows/acceptance-py3.6.yml @@ -91,6 +91,9 @@ jobs: - name: webpack if: steps.changes.outputs.backend == 'true' + env: + SENTRY_INSTRUMENTATION: 1 + SENTRY_WEBPACK_WEBHOOK_SECRET: ${{ secrets.SENTRY_WEBPACK_WEBHOOK_SECRET }} run: | yarn webpack --display errors-only diff --git a/.github/workflows/acceptance.yml b/.github/workflows/acceptance.yml index 10d93820896e40..c4c43debb8f748 100644 --- a/.github/workflows/acceptance.yml +++ b/.github/workflows/acceptance.yml @@ -151,6 +151,9 @@ jobs: yarn install --frozen-lockfile - name: webpack + env: + SENTRY_INSTRUMENTATION: 1 + SENTRY_WEBPACK_WEBHOOK_SECRET: ${{ secrets.SENTRY_WEBPACK_WEBHOOK_SECRET }} run: | yarn webpack --display errors-only diff --git a/.github/workflows/js-build-and-lint.yml b/.github/workflows/js-build-and-lint.yml index 375e277a3e027c..7c0ee964e7b9c4 100644 --- a/.github/workflows/js-build-and-lint.yml +++ b/.github/workflows/js-build-and-lint.yml @@ -139,6 +139,9 @@ jobs: - uses: getsentry/size-limit-action@v3 if: github.ref == 'refs/heads/master' || steps.changes.outputs.frontend == 'true' + env: + SENTRY_INSTRUMENTATION: 1 + SENTRY_WEBPACK_WEBHOOK_SECRET: ${{ secrets.SENTRY_WEBPACK_WEBHOOK_SECRET }} with: main_branch: master workflow_name: 'js-build-and-lint' diff --git a/build-utils/sentry-instrumentation.js b/build-utils/sentry-instrumentation.js index f1c0a696b0ff9e..60da9b3d5abde1 100644 --- a/build-utils/sentry-instrumentation.js +++ b/build-utils/sentry-instrumentation.js @@ -8,24 +8,23 @@ const { NODE_ENV, SENTRY_INSTRUMENTATION, SENTRY_WEBPACK_WEBHOOK_SECRET, - TRAVIS_COMMIT, - TRAVIS_BRANCH, - TRAVIS_PULL_REQUEST, - TRAVIS_PULL_REQUEST_BRANCH, + GITHUB_SHA, + GITHUB_REF, } = process.env; -const IS_CI = !!TRAVIS_COMMIT; +const IS_CI = !!GITHUB_SHA; const PLUGIN_NAME = 'SentryInstrumentation'; const GB_BYTE = 1073741824; -const createSignature = function(secret, payload) { +const createSignature = function (secret, payload) { const hmac = crypto.createHmac('sha1', secret); return `sha1=${hmac.update(payload).digest('hex')}`; }; class SentryInstrumentation { constructor() { - // Only run if SENTRY_INSTRUMENTATION` is set or when in travis, only in the javascript suite that runs webpack + // Only run if SENTRY_INSTRUMENTATION` is set or when in ci, + // only in the javascript suite that runs webpack if (!SENTRY_INSTRUMENTATION) { return; } @@ -41,8 +40,7 @@ class SentryInstrumentation { }); if (IS_CI) { - this.Sentry.setTag('branch', TRAVIS_PULL_REQUEST_BRANCH || TRAVIS_BRANCH); - this.Sentry.setTag('pull_request', TRAVIS_PULL_REQUEST); + this.Sentry.setTag('branch', GITHUB_REF); } const cpus = os.cpus(); @@ -74,8 +72,7 @@ class SentryInstrumentation { file, entrypointName, size, - commit: TRAVIS_COMMIT, - pull_request_number: TRAVIS_PULL_REQUEST, + commit: GITHUB_SHA, environment: IS_CI ? 'ci' : '', node_env: NODE_ENV, }); @@ -118,9 +115,9 @@ class SentryInstrumentation { data: { os: `${os.platform()} ${os.arch()} v${os.release()}`, memory: os.freemem() - ? `${os.freemem() / GB_BYTE} / ${os.totalmem() / GB_BYTE} GB (${(os.freemem() / - os.totalmem()) * - 100}% free)` + ? `${os.freemem() / GB_BYTE} / ${os.totalmem() / GB_BYTE} GB (${ + (os.freemem() / os.totalmem()) * 100 + }% free)` : 'N/A', loadavg: os.loadavg(), },
d8973eb6bb2bc9e2ebf2052977393ac86e55b9ba
2024-10-07 21:45:53
Malachi Willey
chore(issue-stream): Add feature flag for stream table layout changes (#78680)
false
Add feature flag for stream table layout changes (#78680)
chore
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py index 7021720b181c31..d5508881729c87 100644 --- a/src/sentry/features/temporary.py +++ b/src/sentry/features/temporary.py @@ -184,6 +184,8 @@ def register_temporary_features(manager: FeatureManager): manager.add("organizations:issue-search-snuba", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False) # Enable the new issue stream search bar UI manager.add("organizations:issue-stream-search-query-builder", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True) + # Enable issue stream table layout changes + manager.add("organizations:issue-stream-table-layout", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=True) manager.add("organizations:large-debug-files", OrganizationFeature, FeatureHandlerStrategy.INTERNAL, api_expose=False) # Enabled latest adopted release filter for issue alerts manager.add("organizations:latest-adopted-release-filter", OrganizationFeature, FeatureHandlerStrategy.FLAGPOLE, api_expose=False)
8f53000b026f763fb849c40c7fb05277e22bb2c9
2022-11-09 00:01:33
Malachi Willey
feat(saved-searches): Make search pinning use react-query (#41110)
false
Make search pinning use react-query (#41110)
feat
diff --git a/static/app/views/issueList/issueListSetAsDefault.spec.tsx b/static/app/views/issueList/issueListSetAsDefault.spec.tsx index 97881262d3018b..7130a637304a96 100644 --- a/static/app/views/issueList/issueListSetAsDefault.spec.tsx +++ b/static/app/views/issueList/issueListSetAsDefault.spec.tsx @@ -1,7 +1,7 @@ import {initializeOrg} from 'sentry-test/initializeOrg'; -import {render, screen, userEvent} from 'sentry-test/reactTestingLibrary'; +import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary'; -import {SavedSearchType} from 'sentry/types'; +import {SavedSearchType, SavedSearchVisibility} from 'sentry/types'; import IssueListSetAsDefault from 'sentry/views/issueList/issueListSetAsDefault'; describe('IssueListSetAsDefault', () => { @@ -24,26 +24,31 @@ describe('IssueListSetAsDefault', () => { ...routerProps, }; - it('can set a search as default', () => { + it('can set a search as default', async () => { const mockPinSearch = MockApiClient.addMockResponse({ url: '/organizations/org-slug/pinned-searches/', method: 'PUT', - body: {}, + body: TestStubs.Search({ + isPinned: true, + visibility: SavedSearchVisibility.OwnerPinned, + }), }); render(<IssueListSetAsDefault {...defaultProps} />); userEvent.click(screen.getByRole('button', {name: /set as default/i})); - expect(mockPinSearch).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - data: {query: 'is:unresolved', sort: 'date', type: SavedSearchType.ISSUE}, - }) - ); + await waitFor(() => { + expect(mockPinSearch).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + data: {query: 'is:unresolved', sort: 'date', type: SavedSearchType.ISSUE}, + }) + ); + }); }); - it('can remove a default search', () => { + it('can remove a default search', async () => { const mockUnpinSearch = MockApiClient.addMockResponse({ url: '/organizations/org-slug/pinned-searches/', method: 'DELETE', @@ -58,11 +63,13 @@ describe('IssueListSetAsDefault', () => { userEvent.click(screen.getByRole('button', {name: /remove default/i})); - expect(mockUnpinSearch).toHaveBeenCalledWith( - expect.anything(), - expect.objectContaining({ - data: {type: SavedSearchType.ISSUE}, - }) - ); + await waitFor(() => { + expect(mockUnpinSearch).toHaveBeenCalledWith( + expect.anything(), + expect.objectContaining({ + data: {type: SavedSearchType.ISSUE}, + }) + ); + }); }); }); diff --git a/static/app/views/issueList/issueListSetAsDefault.tsx b/static/app/views/issueList/issueListSetAsDefault.tsx index 75afc9a67ae667..320ce985812eda 100644 --- a/static/app/views/issueList/issueListSetAsDefault.tsx +++ b/static/app/views/issueList/issueListSetAsDefault.tsx @@ -2,14 +2,14 @@ import {browserHistory, withRouter, WithRouterProps} from 'react-router'; import isNil from 'lodash/isNil'; -import {pinSearch, unpinSearch} from 'sentry/actionCreators/savedSearches'; import Button from 'sentry/components/button'; import {removeSpace} from 'sentry/components/smartSearchBar/utils'; import {IconBookmark} from 'sentry/icons'; import {t} from 'sentry/locale'; import {Organization, SavedSearch, SavedSearchType} from 'sentry/types'; import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent'; -import useApi from 'sentry/utils/useApi'; +import {usePinSearch} from 'sentry/views/issueList/mutations/usePinSearch'; +import {useUnpinSearch} from 'sentry/views/issueList/mutations/useUnpinSearch'; interface IssueListSetAsDefaultProps extends WithRouterProps { organization: Organization; @@ -25,52 +25,51 @@ const IssueListSetAsDefault = ({ sort, query, }: IssueListSetAsDefaultProps) => { - const api = useApi(); const pinnedSearch = savedSearch?.isPinned ? savedSearch : undefined; const pinnedSearchActive = !isNil(pinnedSearch); - const onTogglePinnedSearch = async () => { - const {cursor: _cursor, page: _page, ...currentQuery} = location.query; - - trackAdvancedAnalyticsEvent('search.pin', { - organization, - action: pinnedSearch ? 'unpin' : 'pin', - search_type: 'issues', - query: pinnedSearch?.query ?? query, - }); - - if (pinnedSearch) { - await unpinSearch(api, organization.slug, SavedSearchType.ISSUE, pinnedSearch); + const {mutate: pinSearch, isLoading: isPinning} = usePinSearch({ + onSuccess: response => { + const {cursor: _cursor, page: _page, ...currentQuery} = location.query; + browserHistory.push({ + ...location, + pathname: `/organizations/${organization.slug}/issues/searches/${response.id}/`, + query: {referrer: 'search-bar', ...currentQuery}, + }); + }, + }); + const {mutate: unpinSearch, isLoading: isUnpinning} = useUnpinSearch({ + onSuccess: () => { + const {cursor: _cursor, page: _page, ...currentQuery} = location.query; browserHistory.push({ ...location, pathname: `/organizations/${organization.slug}/issues/`, query: { referrer: 'search-bar', ...currentQuery, - query: pinnedSearch.query, - sort: pinnedSearch.sort, }, }); - return; - } + }, + }); - const resp = await pinSearch( - api, - organization.slug, - SavedSearchType.ISSUE, - removeSpace(query), - sort - ); + const onTogglePinnedSearch = () => { + trackAdvancedAnalyticsEvent('search.pin', { + organization, + action: pinnedSearch ? 'unpin' : 'pin', + search_type: 'issues', + query: pinnedSearch?.query ?? query, + }); - if (!resp || !resp.id) { - return; + if (pinnedSearch) { + unpinSearch({orgSlug: organization.slug, type: SavedSearchType.ISSUE}); + } else { + pinSearch({ + orgSlug: organization.slug, + type: SavedSearchType.ISSUE, + query: removeSpace(query), + sort, + }); } - - browserHistory.push({ - ...location, - pathname: `/organizations/${organization.slug}/issues/searches/${resp.id}/`, - query: {referrer: 'search-bar', ...currentQuery}, - }); }; if (!organization.features.includes('issue-list-saved-searches-v2')) { @@ -82,6 +81,7 @@ const IssueListSetAsDefault = ({ onClick={onTogglePinnedSearch} size="sm" icon={<IconBookmark isSolid={pinnedSearchActive} />} + disabled={isPinning || isUnpinning} > {pinnedSearchActive ? t('Remove Default') : t('Set as Default')} </Button> diff --git a/static/app/views/issueList/mutations/usePinSearch.tsx b/static/app/views/issueList/mutations/usePinSearch.tsx new file mode 100644 index 00000000000000..39e8159fb548f9 --- /dev/null +++ b/static/app/views/issueList/mutations/usePinSearch.tsx @@ -0,0 +1,52 @@ +import {addErrorMessage} from 'sentry/actionCreators/indicator'; +import {t} from 'sentry/locale'; +import {SavedSearch, SavedSearchType} from 'sentry/types'; +import {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'; + +type PinSavedSearchVariables = { + orgSlug: string; + query: string; + sort: string | null; + type: SavedSearchType; +}; + +type PinSavedSearchResponse = SavedSearch; + +export const usePinSearch = ( + options: Omit< + UseMutationOptions<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>, + 'mutationFn' + > = {} +) => { + const api = useApi(); + const queryClient = useQueryClient(); + + return useMutation<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>({ + ...options, + mutationFn: ({orgSlug, query, type, sort}) => + api.requestPromise(`/organizations/${orgSlug}/pinned-searches/`, { + method: 'PUT', + data: {query, type, sort}, + }), + onSuccess: (savedSearch, variables, context) => { + queryClient.setQueryData( + makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}), + oldData => { + if (!Array.isArray(oldData)) { + return oldData; + } + + return [savedSearch, ...oldData]; + } + ); + options.onSuccess?.(savedSearch, variables, context); + }, + onError: (error, variables, context) => { + addErrorMessage(t('Failed to pin search.')); + options.onError?.(error, variables, context); + }, + }); +}; diff --git a/static/app/views/issueList/mutations/useUnpinSearch.tsx b/static/app/views/issueList/mutations/useUnpinSearch.tsx new file mode 100644 index 00000000000000..4d51b75f057060 --- /dev/null +++ b/static/app/views/issueList/mutations/useUnpinSearch.tsx @@ -0,0 +1,54 @@ +import {addErrorMessage} from 'sentry/actionCreators/indicator'; +import {t} from 'sentry/locale'; +import {SavedSearch, SavedSearchType, SavedSearchVisibility} from 'sentry/types'; +import {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'; + +type UnpinSavedSearchVariables = { + orgSlug: string; + type: SavedSearchType; +}; + +type UnpinSavedSearchResponse = {type: SavedSearchType}; + +export const useUnpinSearch = ( + options: Omit< + UseMutationOptions<UnpinSavedSearchResponse, RequestError, UnpinSavedSearchVariables>, + 'mutationFn' + > = {} +) => { + const api = useApi(); + const queryClient = useQueryClient(); + + return useMutation<UnpinSavedSearchResponse, RequestError, UnpinSavedSearchVariables>({ + ...options, + mutationFn: ({orgSlug, type}) => + api.requestPromise(`/organizations/${orgSlug}/pinned-searches/`, { + method: 'DELETE', + data: { + type, + }, + }), + onSuccess: (savedSearch, variables, context) => { + queryClient.setQueryData<SavedSearch[]>( + makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}), + oldData => { + if (!Array.isArray(oldData)) { + return oldData; + } + + return oldData.filter( + search => search.visibility === SavedSearchVisibility.OwnerPinned + ); + } + ); + options.onSuccess?.(savedSearch, variables, context); + }, + onError: (error, variables, context) => { + addErrorMessage(t('Failed to unpin search.')); + options.onError?.(error, variables, context); + }, + }); +};
69023be58d24771a0b1d4d597377b8a6e16596c6
2021-07-22 23:39:38
Dora
fix(grammar): autogroup to autogrouped (#27680)
false
autogroup to autogrouped (#27680)
fix
diff --git a/static/app/components/events/interfaces/spans/spanGroupBar.tsx b/static/app/components/events/interfaces/spans/spanGroupBar.tsx index 176f89be6c4464..70c15c26f5d83b 100644 --- a/static/app/components/events/interfaces/spans/spanGroupBar.tsx +++ b/static/app/components/events/interfaces/spans/spanGroupBar.tsx @@ -181,8 +181,8 @@ class SpanGroupBar extends React.Component<Props> { ); return ( - <strong>{`${t('Autogroup spans')} \u2014 ${mostFrequentOperationName}${ - hasOthers ? t(' and others') : '' + <strong>{`${t('Autogrouped ')}\u2014 ${mostFrequentOperationName}${ + hasOthers ? t(' and more') : '' }`}</strong> ); }
0fd7c6fc765409cb234f59e1e73fb15a5436c000
2022-05-12 04:51:49
Aniket Das
ref(apidocs): Leverage inheritance to consolidate repeated fields (#34518)
false
Leverage inheritance to consolidate repeated fields (#34518)
ref
diff --git a/src/sentry/api/endpoints/organization_projects.py b/src/sentry/api/endpoints/organization_projects.py index e01e613c490305..28ea552a48f240 100644 --- a/src/sentry/api/endpoints/organization_projects.py +++ b/src/sentry/api/endpoints/organization_projects.py @@ -10,7 +10,7 @@ from sentry.api.paginator import OffsetPaginator from sentry.api.serializers import serialize from sentry.api.serializers.models.project import ( - OrganizationProjectResponseDict, + OrganizationProjectResponse, ProjectSummarySerializer, ) from sentry.apidocs.constants import RESPONSE_FORBIDDEN, RESPONSE_NOTFOUND, RESPONSE_UNAUTHORIZED @@ -32,7 +32,7 @@ class OrganizationProjectsEndpoint(OrganizationEndpoint, EnvironmentMixin): request=None, responses={ 200: inline_sentry_response_serializer( - "OrganizationProjectResponseDict", List[OrganizationProjectResponseDict] + "OrganizationProjectResponseDict", List[OrganizationProjectResponse] ), 401: RESPONSE_UNAUTHORIZED, 403: RESPONSE_FORBIDDEN, diff --git a/src/sentry/api/serializers/models/project.py b/src/sentry/api/serializers/models/project.py index 8ea55f451a593f..43e53967159159 100644 --- a/src/sentry/api/serializers/models/project.py +++ b/src/sentry/api/serializers/models/project.py @@ -165,23 +165,32 @@ def get_features_for_projects( return features_by_project -class ProjectSerializerResponse(TypedDict): +class _ProjectSerializerOptionalBaseResponse(TypedDict, total=False): + stats: Any + transactionStats: Any + sessionStats: Any + + +class ProjectSerializerBaseResponse(_ProjectSerializerOptionalBaseResponse): id: str - slug: str name: str # TODO: add deprecation about this field (not used in app) - isPublic: bool + slug: str isBookmarked: bool - color: str + isMember: bool + hasAccess: bool dateCreated: datetime - firstEvent: datetime + features: List[str] firstTransactionEvent: bool hasSessions: bool - features: List[str] + platform: Optional[str] + firstEvent: Optional[datetime] + + +class ProjectSerializerResponse(ProjectSerializerBaseResponse): + isPublic: bool + color: str status: str # TODO enum/literal - platform: str isInternal: bool - isMember: bool - hasAccess: bool avatar: Any # TODO: use Avatar type from other serializers @@ -494,31 +503,18 @@ class LatestReleaseDict(TypedDict): version: str -class _OrganizationProjectResponseDictOptional(TypedDict, total=False): +class _OrganizationProjectOptionalResponse(TypedDict, total=False): latestDeploys: Optional[Dict[str, Dict[str, str]]] - stats: Any - transactionStats: Any - sessionStats: Any -class OrganizationProjectResponseDict(_OrganizationProjectResponseDictOptional): +class OrganizationProjectResponse( + _OrganizationProjectOptionalResponse, ProjectSerializerBaseResponse +): team: Optional[TeamResponseDict] teams: List[TeamResponseDict] - id: str - name: str - slug: str - isBookmarked: bool - isMember: bool - hasAccess: bool - dateCreated: str eventProcessing: EventProcessingDict - features: List[str] - firstTransactionEvent: bool - hasSessions: bool - platform: Optional[str] platforms: List[str] hasUserReports: bool - firstEvent: Optional[str] environments: List[str] latestRelease: Optional[LatestReleaseDict] @@ -620,8 +616,8 @@ def get_attrs( return attrs - def serialize(self, obj, attrs, user) -> OrganizationProjectResponseDict: # type: ignore - context = OrganizationProjectResponseDict( + def serialize(self, obj, attrs, user) -> OrganizationProjectResponse: # type: ignore + context = OrganizationProjectResponse( team=attrs["teams"][0] if attrs["teams"] else None, teams=attrs["teams"], id=str(obj.id),
6aff6d241321f34a1d48fa401ba656829acd8a85
2021-09-01 23:01:26
Kelly Carino
fix(alerts): Project breadcrumb link to project rule list (#28339)
false
Project breadcrumb link to project rule list (#28339)
fix
diff --git a/static/app/views/alerts/builder/builderBreadCrumbs.tsx b/static/app/views/alerts/builder/builderBreadCrumbs.tsx index 10342a7ae79d5f..4da823eb58c4e0 100644 --- a/static/app/views/alerts/builder/builderBreadCrumbs.tsx +++ b/static/app/views/alerts/builder/builderBreadCrumbs.tsx @@ -39,7 +39,7 @@ function BuilderBreadCrumbs(props: Props) { const isSuperuser = isActiveSuperuser(); const projectCrumbLink = { - to: `/settings/${orgSlug}/projects/${projectSlug}/`, + to: `/organizations/${orgSlug}/alerts/rules/?project=${project?.id}`, label: <IdBadge project={project} avatarSize={18} disableLink />, preserveGlobalSelection: true, };
159935349d28f02c48c89006d6158eadd7342bf7
2018-01-25 03:12:16
Lyn Nagara
test: Add tests for Project Alert rule component
false
Add tests for Project Alert rule component
test
diff --git a/tests/js/setup.js b/tests/js/setup.js index 2449d9dad40c1a..5f4c1aa50235c9 100644 --- a/tests/js/setup.js +++ b/tests/js/setup.js @@ -366,6 +366,29 @@ window.TestStubs = { ...params, }; }, + ProjectAlertRule: () => { + return { + id: '1', + }; + }, + ProjectAlertRuleConfiguration: () => { + return { + actions: [ + { + html: 'Send a notification for all services', + id: 'sentry.rules.actions.notify1', + label: 'Send a notification for all services', + }, + ], + conditions: [ + { + html: 'An event is seen', + id: 'sentry.rules.conditions.1', + label: 'An event is seen', + }, + ], + }; + }, }; // this is very commonly used, so expose it globally diff --git a/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap b/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap new file mode 100644 index 00000000000000..ccb377b5319727 --- /dev/null +++ b/tests/js/spec/views/__snapshots__/projectAlertRuleDetails.spec.jsx.snap @@ -0,0 +1,841 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`ProjectAlertRuleDetails Edit alert rule renders 1`] = ` +<ProjectAlertRuleDetails + params={ + Object { + "orgId": "org-slug", + "projectId": "project-slug", + } + } +> + <SideEffect(DocumentTitle) + title="Sentry" + > + <DocumentTitle + title="Sentry" + > + <RuleEditor + actions={ + Array [ + Object { + "html": "Send a notification for all services", + "id": "sentry.rules.actions.notify1", + "label": "Send a notification for all services", + }, + ] + } + conditions={ + Array [ + Object { + "html": "An event is seen", + "id": "sentry.rules.conditions.1", + "label": "An event is seen", + }, + ] + } + organization={ + Object { + "access": Array [ + "org:read", + "org:write", + "org:admin", + "project:read", + "project:write", + "project:admin", + "team:read", + "team:write", + "team:admin", + ], + "features": Array [], + "id": "3", + "name": "Organization Name", + "onboardingTasks": Array [], + "slug": "org-slug", + "status": Object { + "id": "active", + "name": "active", + }, + "teams": Array [], + } + } + params={ + Object { + "orgId": "org-slug", + "projectId": "project-slug", + } + } + project={ + Object { + "digestsMaxDelay": 60, + "digestsMinDelay": 5, + "id": "2", + "name": "Project Name", + "slug": "project-slug", + "subjectTemplate": "[$project] \${tag:level}: $title", + } + } + > + <form + onSubmit={[Function]} + > + <div + className="box rule-detail" + > + <div + className="box-header" + > + <h3> + New Alert Rule + </h3> + </div> + <div + className="box-content with-padding" + > + <h6> + Rule name + : + </h6> + <div + className="control-group" + > + <input + className="form-control" + defaultValue="" + placeholder="My Rule Name" + required={true} + type="text" + /> + </div> + <hr /> + <div + className="node-match-selector" + > + <h6> + Every time + <SelectInput + className="" + disabled={false} + key="1" + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 80, + } + } + value="all" + > + <select + className="" + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 80, + } + } + value="all" + > + <option + value="all" + > + all + </option> + <option + value="any" + > + any + </option> + <option + value="none" + > + none + </option> + </select> + </SelectInput> + of these conditions are met: + </h6> + </div> + <RuleNodeList + className="rule-condition-list" + initialItems={Array []} + nodes={ + Array [ + Object { + "html": "An event is seen", + "id": "sentry.rules.conditions.1", + "label": "An event is seen", + }, + ] + } + > + <div + className="rule-condition-list" + > + <table + className="node-list table" + style={ + Object { + "marginBottom": "10px", + } + } + > + <tbody /> + </table> + <fieldset + className="node-selector" + > + <SelectInput + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <select + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <option + key="blank" + /> + <option + key="sentry.rules.conditions.1" + value="sentry.rules.conditions.1" + > + An event is seen + </option> + </select> + </SelectInput> + </fieldset> + </div> + </RuleNodeList> + <hr /> + <h6> + Take these actions: + </h6> + <RuleNodeList + className="rule-action-list" + initialItems={Array []} + nodes={ + Array [ + Object { + "html": "Send a notification for all services", + "id": "sentry.rules.actions.notify1", + "label": "Send a notification for all services", + }, + ] + } + > + <div + className="rule-action-list" + > + <table + className="node-list table" + style={ + Object { + "marginBottom": "10px", + } + } + > + <tbody /> + </table> + <fieldset + className="node-selector" + > + <SelectInput + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <select + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <option + key="blank" + /> + <option + key="sentry.rules.actions.notify1" + value="sentry.rules.actions.notify1" + > + Send a notification for all services + </option> + </select> + </SelectInput> + </fieldset> + </div> + </RuleNodeList> + <hr /> + <div + className="node-frequency-selector" + > + <h6> + <span + key="4" + > + <span + key="0" + > + Perform these actions at most once every + </span> + <SelectInput + className="" + disabled={false} + key="1" + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 150, + } + } + value={30} + > + <select + className="" + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 150, + } + } + value={30} + > + <option + value="5" + > + 5 minutes + </option> + <option + value="10" + > + 10 minutes + </option> + <option + value="30" + > + 30 minutes + </option> + <option + value="60" + > + 60 minutes + </option> + <option + value="180" + > + 3 hours + </option> + <option + value="720" + > + 12 hours + </option> + <option + value="1440" + > + 24 hours + </option> + <option + value="10080" + > + one week + </option> + <option + value="43200" + > + 30 days + </option> + </select> + </SelectInput> + <span + key="2" + > + for an issue. + </span> + </span> + </h6> + </div> + <div + className="actions" + > + <button + className="btn btn-primary btn-lg" + disabled={false} + > + Save Rule + </button> + </div> + </div> + </div> + </form> + </RuleEditor> + </DocumentTitle> + </SideEffect(DocumentTitle)> +</ProjectAlertRuleDetails> +`; + +exports[`ProjectAlertRuleDetails New alert rule renders 1`] = ` +<ProjectAlertRuleDetails + params={ + Object { + "orgId": "org-slug", + "projectId": "project-slug", + } + } +> + <SideEffect(DocumentTitle) + title="Sentry" + > + <DocumentTitle + title="Sentry" + > + <RuleEditor + actions={ + Array [ + Object { + "html": "Send a notification for all services", + "id": "sentry.rules.actions.notify1", + "label": "Send a notification for all services", + }, + ] + } + conditions={ + Array [ + Object { + "html": "An event is seen", + "id": "sentry.rules.conditions.1", + "label": "An event is seen", + }, + ] + } + organization={ + Object { + "access": Array [ + "org:read", + "org:write", + "org:admin", + "project:read", + "project:write", + "project:admin", + "team:read", + "team:write", + "team:admin", + ], + "features": Array [], + "id": "3", + "name": "Organization Name", + "onboardingTasks": Array [], + "slug": "org-slug", + "status": Object { + "id": "active", + "name": "active", + }, + "teams": Array [], + } + } + params={ + Object { + "orgId": "org-slug", + "projectId": "project-slug", + } + } + project={ + Object { + "digestsMaxDelay": 60, + "digestsMinDelay": 5, + "id": "2", + "name": "Project Name", + "slug": "project-slug", + "subjectTemplate": "[$project] \${tag:level}: $title", + } + } + > + <form + onSubmit={[Function]} + > + <div + className="box rule-detail" + > + <div + className="box-header" + > + <h3> + New Alert Rule + </h3> + </div> + <div + className="box-content with-padding" + > + <h6> + Rule name + : + </h6> + <div + className="control-group" + > + <input + className="form-control" + defaultValue="" + placeholder="My Rule Name" + required={true} + type="text" + /> + </div> + <hr /> + <div + className="node-match-selector" + > + <h6> + Every time + <SelectInput + className="" + disabled={false} + key="1" + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 80, + } + } + value="all" + > + <select + className="" + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 80, + } + } + value="all" + > + <option + value="all" + > + all + </option> + <option + value="any" + > + any + </option> + <option + value="none" + > + none + </option> + </select> + </SelectInput> + of these conditions are met: + </h6> + </div> + <RuleNodeList + className="rule-condition-list" + initialItems={Array []} + nodes={ + Array [ + Object { + "html": "An event is seen", + "id": "sentry.rules.conditions.1", + "label": "An event is seen", + }, + ] + } + > + <div + className="rule-condition-list" + > + <table + className="node-list table" + style={ + Object { + "marginBottom": "10px", + } + } + > + <tbody /> + </table> + <fieldset + className="node-selector" + > + <SelectInput + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <select + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <option + key="blank" + /> + <option + key="sentry.rules.conditions.1" + value="sentry.rules.conditions.1" + > + An event is seen + </option> + </select> + </SelectInput> + </fieldset> + </div> + </RuleNodeList> + <hr /> + <h6> + Take these actions: + </h6> + <RuleNodeList + className="rule-action-list" + initialItems={Array []} + nodes={ + Array [ + Object { + "html": "Send a notification for all services", + "id": "sentry.rules.actions.notify1", + "label": "Send a notification for all services", + }, + ] + } + > + <div + className="rule-action-list" + > + <table + className="node-list table" + style={ + Object { + "marginBottom": "10px", + } + } + > + <tbody /> + </table> + <fieldset + className="node-selector" + > + <SelectInput + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <select + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={false} + style={ + Object { + "width": "100%", + } + } + value="" + > + <option + key="blank" + /> + <option + key="sentry.rules.actions.notify1" + value="sentry.rules.actions.notify1" + > + Send a notification for all services + </option> + </select> + </SelectInput> + </fieldset> + </div> + </RuleNodeList> + <hr /> + <div + className="node-frequency-selector" + > + <h6> + <span + key="4" + > + <span + key="0" + > + Perform these actions at most once every + </span> + <SelectInput + className="" + disabled={false} + key="1" + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 150, + } + } + value={30} + > + <select + className="" + disabled={false} + multiple={false} + onChange={[Function]} + placeholder="Select an option..." + required={true} + style={ + Object { + "width": 150, + } + } + value={30} + > + <option + value="5" + > + 5 minutes + </option> + <option + value="10" + > + 10 minutes + </option> + <option + value="30" + > + 30 minutes + </option> + <option + value="60" + > + 60 minutes + </option> + <option + value="180" + > + 3 hours + </option> + <option + value="720" + > + 12 hours + </option> + <option + value="1440" + > + 24 hours + </option> + <option + value="10080" + > + one week + </option> + <option + value="43200" + > + 30 days + </option> + </select> + </SelectInput> + <span + key="2" + > + for an issue. + </span> + </span> + </h6> + </div> + <div + className="actions" + > + <button + className="btn btn-primary btn-lg" + disabled={false} + > + Save Rule + </button> + </div> + </div> + </div> + </form> + </RuleEditor> + </DocumentTitle> + </SideEffect(DocumentTitle)> +</ProjectAlertRuleDetails> +`; diff --git a/tests/js/spec/views/projectAlertRuleDetails.spec.jsx b/tests/js/spec/views/projectAlertRuleDetails.spec.jsx new file mode 100644 index 00000000000000..3dc5c013b9f4b5 --- /dev/null +++ b/tests/js/spec/views/projectAlertRuleDetails.spec.jsx @@ -0,0 +1,128 @@ +import React from 'react'; +import {mount} from 'enzyme'; +import {browserHistory} from 'react-router'; + +import {Client} from 'app/api'; + +import ProjectAlertRuleDetails from 'app/views/projectAlertRuleDetails'; + +jest.mock('jquery'); + +describe('ProjectAlertRuleDetails', function() { + let sandbox, replaceState; + beforeEach(function() { + sandbox = sinon.sandbox.create(); + Client.clearMockResponses(); + MockApiClient.addMockResponse({ + url: '/projects/org-slug/project-slug/rules/configuration/', + method: 'GET', + body: TestStubs.ProjectAlertRuleConfiguration(), + }); + Client.addMockResponse({ + url: '/projects/org-slug/project-slug/rules/1/', + method: 'GET', + body: TestStubs.ProjectAlertRule(), + }); + + replaceState = sandbox.stub(browserHistory, 'replace'); + }); + + afterEach(function() { + sandbox.restore(); + }); + + describe('New alert rule', function() { + let wrapper, mock; + beforeEach(function() { + mock = Client.addMockResponse({ + url: '/projects/org-slug/project-slug/rules/', + method: 'POST', + body: TestStubs.ProjectAlertRule(), + }); + + wrapper = mount( + <ProjectAlertRuleDetails + params={{orgId: 'org-slug', projectId: 'project-slug'}} + />, + { + context: { + project: TestStubs.Project(), + organization: TestStubs.Organization(), + }, + } + ); + }); + it('renders', function() { + expect(wrapper).toMatchSnapshot(); + }); + + it('sets defaults', function() { + let selects = wrapper.find('select'); + expect(selects.first().props().value).toBe('all'); + expect(selects.last().props().value).toBe(30); + }); + + // TODO: Rewrite the rule editor to not use ReactDOM.findDOMNode so this can be tested + xdescribe('update', function() { + let name; + beforeEach(function() { + name = wrapper.find('input').first(); + name.value = 'My rule'; + name.simulate('change'); + + wrapper.find('form').simulate('submit'); + }); + + it('sends create request on save', function() { + expect(mock).toHaveBeenCalled(); + + expect(mock.mock.calls[0][1]).toMatchObject({ + data: { + name: 'My rule', + }, + }); + }); + + it('updates URL', function() { + let url = '/org-slug/project-slug/settings/alerts/rules/1/'; + expect(replaceState.calledWith(url)).toBe(true); + }); + }); + }); + + describe('Edit alert rule', function() { + let wrapper, mock; + beforeEach(function() { + mock = Client.addMockResponse({ + url: '/projects/org-slug/project-slug/rules/', + method: 'PUT', + body: TestStubs.ProjectAlertRule(), + }); + + wrapper = mount( + <ProjectAlertRuleDetails + params={{orgId: 'org-slug', projectId: 'project-slug'}} + />, + { + context: { + project: TestStubs.Project(), + organization: TestStubs.Organization(), + }, + } + ); + }); + it('renders', function() { + expect(wrapper).toMatchSnapshot(); + }); + + // TODO: Rewrite the rule editor to not use ReactDOM.findDOMNode so this can be tested + xit('updates', function() { + let name = wrapper.find('input').first(); + name.value = 'My rule'; + name.simulate('change'); + + wrapper.find('form').simulate('submit'); + expect(mock).toHaveBeenCalled(); + }); + }); +});