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
⌀ |
|---|---|---|---|---|---|---|---|
83ce079c7c35384b97e187bc451a0c24c9aa6cca
|
2024-10-29 22:11:01
|
Richard Roggenkemper
|
feat(issue-details): Add representative priority to activity (#79878)
| false
|
Add representative priority to activity (#79878)
|
feat
|
diff --git a/static/app/views/issueDetails/streamline/activitySection.tsx b/static/app/views/issueDetails/streamline/activitySection.tsx
index 3c53694c1731eb..2286fa026fddee 100644
--- a/static/app/views/issueDetails/streamline/activitySection.tsx
+++ b/static/app/views/issueDetails/streamline/activitySection.tsx
@@ -49,7 +49,8 @@ function TimelineItem({
teams
);
- const Icon = groupActivityTypeIconMapping[item.type]?.Component ?? null;
+ const iconMapping = groupActivityTypeIconMapping[item.type];
+ const Icon = iconMapping?.Component ?? null;
return (
<ActivityTimelineItem
@@ -66,7 +67,11 @@ function TimelineItem({
timestamp={<Timestamp date={item.dateCreated} tooltipProps={{skipWrapper: true}} />}
icon={
Icon && (
- <Icon {...groupActivityTypeIconMapping[item.type].defaultProps} size="xs" />
+ <Icon
+ {...iconMapping.defaultProps}
+ {...iconMapping.propsFunction?.(item.data)}
+ size="xs"
+ />
)
}
>
diff --git a/static/app/views/issueDetails/streamline/groupActivityIcons.tsx b/static/app/views/issueDetails/streamline/groupActivityIcons.tsx
index e5063ace83b9ef..dcf8d2d3317063 100644
--- a/static/app/views/issueDetails/streamline/groupActivityIcons.tsx
+++ b/static/app/views/issueDetails/streamline/groupActivityIcons.tsx
@@ -23,6 +23,7 @@ import {GroupActivityType} from 'sentry/types/group';
interface IconWithDefaultProps {
Component: React.ComponentType<any> | null;
defaultProps: {locked?: boolean; type?: string};
+ propsFunction?: (props: any) => any;
}
export const groupActivityTypeIconMapping: Record<
@@ -63,6 +64,22 @@ export const groupActivityTypeIconMapping: Record<
Component: IconGraph,
defaultProps: {type: 'area'},
},
- [GroupActivityType.SET_PRIORITY]: {Component: IconCellSignal, defaultProps: {}},
+ [GroupActivityType.SET_PRIORITY]: {
+ Component: IconCellSignal,
+ defaultProps: {},
+ propsFunction: data => {
+ const {priority} = data;
+ switch (priority) {
+ case 'high':
+ return {bars: 3};
+ case 'medium':
+ return {bars: 2};
+ case 'low':
+ return {bars: 1};
+ default:
+ return {bars: 0};
+ }
+ },
+ },
[GroupActivityType.DELETED_ATTACHMENT]: {Component: IconDelete, defaultProps: {}},
};
|
5b0bd84e0575dd92eb8157b7790bfff8d17d764b
|
2023-03-21 08:21:38
|
Jonas
|
fix(profiling): reenable browser profiling (#46068)
| false
|
reenable browser profiling (#46068)
|
fix
|
diff --git a/static/app/bootstrap/initializeSdk.tsx b/static/app/bootstrap/initializeSdk.tsx
index 759861ce3aaf27..a86864d7c1635f 100644
--- a/static/app/bootstrap/initializeSdk.tsx
+++ b/static/app/bootstrap/initializeSdk.tsx
@@ -20,7 +20,7 @@ const SPA_MODE_ALLOW_URLS = [
// We check for `window.__initialData.user` property and only enable profiling
// for Sentry employees. This is to prevent a Violation error being visible in
// the browser console for our users.
-const shouldEnableBrowserProfiling = false; // window?.__initialData?.user?.isSuperuser;
+const shouldEnableBrowserProfiling = window?.__initialData?.user?.isSuperuser;
/**
* We accept a routes argument here because importing `static/routes`
* is expensive in regards to bundle size. Some entrypoints may opt to forgo
|
a02edf78258761f46b80b4b4b5cadd2f86231821
|
2019-11-27 04:38:06
|
josh
|
ref(django 1.10): port get_field_by_name (#15841)
| false
|
port get_field_by_name (#15841)
|
ref
|
diff --git a/src/sentry/models/group.py b/src/sentry/models/group.py
index f916a23ede49a0..0a369747581fc2 100644
--- a/src/sentry/models/group.py
+++ b/src/sentry/models/group.py
@@ -47,7 +47,7 @@ def parse_short_id(short_id):
short_id = base32_decode(id)
# We need to make sure the short id is not overflowing the
# field's max or the lookup will fail with an assertion error.
- max_id = Group._meta.get_field_by_name("short_id")[0].MAX_VALUE
+ max_id = Group._meta.get_field("short_id").MAX_VALUE
if short_id > max_id:
return None
except ValueError:
|
161676edcff7967e3cfebf07b337c3132f82933b
|
2023-05-19 21:13:47
|
Katie Byers
|
ref(js): Simplify `RequestError` API (#49452)
| false
|
Simplify `RequestError` API (#49452)
|
ref
|
diff --git a/static/app/api.tsx b/static/app/api.tsx
index ebd0a7f7e02b23..45fe445574ba25 100644
--- a/static/app/api.tsx
+++ b/static/app/api.tsx
@@ -13,7 +13,7 @@ import {
import {metric} from 'sentry/utils/analytics';
import getCsrfToken from 'sentry/utils/getCsrfToken';
import {uniqueId} from 'sentry/utils/guid';
-import createRequestError from 'sentry/utils/requestError/createRequestError';
+import RequestError from 'sentry/utils/requestError/requestError';
export class Request {
/**
@@ -598,11 +598,11 @@ export class Client {
}
},
error: (resp: ResponseMeta) => {
- const errorObjectToUse = createRequestError(
- resp,
- preservedError,
+ const errorObjectToUse = new RequestError(
options.method,
- path
+ path,
+ preservedError,
+ resp
);
// Although `this.request` logs all error responses, this error object can
diff --git a/static/app/utils/queryClient.spec.tsx b/static/app/utils/queryClient.spec.tsx
index b29007d4720682..fafb963bb27200 100644
--- a/static/app/utils/queryClient.spec.tsx
+++ b/static/app/utils/queryClient.spec.tsx
@@ -79,10 +79,8 @@ describe('queryClient', function () {
});
it('can return error state', async function () {
- const requestError = new RequestError('GET', '/some/test/path', {
- cause: new Error(),
- });
- requestError.setMessage('something bad happened');
+ const requestError = new RequestError('GET', '/some/test/path', new Error());
+ requestError.message = 'something bad happened';
const api = new MockApiClient();
jest.spyOn(useApi, 'default').mockReturnValue(api);
diff --git a/static/app/utils/requestError/createRequestError.tsx b/static/app/utils/requestError/createRequestError.tsx
deleted file mode 100644
index 9df78ba263e43f..00000000000000
--- a/static/app/utils/requestError/createRequestError.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-import {ResponseMeta} from 'sentry/api';
-
-import RequestError from './requestError';
-
-const ERROR_MAP = {
- 0: 'CancelledError',
- 400: 'BadRequestError',
- 401: 'UnauthorizedError',
- 403: 'ForbiddenError',
- 404: 'NotFoundError',
- 414: 'URITooLongError',
- 426: 'UpgradeRequiredError',
- 429: 'TooManyRequestsError',
- 500: 'InternalServerError',
- 501: 'NotImplementedError',
- 502: 'BadGatewayError',
- 503: 'ServiceUnavailableError',
- 504: 'GatewayTimeoutError',
-};
-
-/**
- * Create a RequestError whose name is equal to HTTP status text defined above
- *
- * @param {Object} resp A XHR response object
- * @param {String} stack The stack trace to use. Helpful for async calls and we want to preserve a different stack.
- */
-export default function createRequestError(
- resp: ResponseMeta,
- cause: Error,
- method: 'POST' | 'GET' | 'DELETE' | 'PUT' | undefined,
- path: string
-) {
- const err = new RequestError(method, path, {cause});
-
- if (resp) {
- const errorName = ERROR_MAP[resp.status];
-
- if (errorName) {
- err.setName(errorName);
- }
-
- err.setResponse(resp);
- }
-
- return err;
-}
diff --git a/static/app/utils/requestError/requestError.tsx b/static/app/utils/requestError/requestError.tsx
index 85e7b382ebc565..990ae09a1d362b 100644
--- a/static/app/utils/requestError/requestError.tsx
+++ b/static/app/utils/requestError/requestError.tsx
@@ -2,9 +2,21 @@ import {ResponseMeta} from 'sentry/api';
import {sanitizePath} from './sanitizePath';
-interface ErrorOptionsObject {
- cause: Error;
-}
+const ERROR_MAP = {
+ 0: 'CancelledError',
+ 400: 'BadRequestError',
+ 401: 'UnauthorizedError',
+ 403: 'ForbiddenError',
+ 404: 'NotFoundError',
+ 414: 'URITooLongError',
+ 426: 'UpgradeRequiredError',
+ 429: 'TooManyRequestsError',
+ 500: 'InternalServerError',
+ 501: 'NotImplementedError',
+ 502: 'BadGatewayError',
+ 503: 'ServiceUnavailableError',
+ 504: 'GatewayTimeoutError',
+};
// Technically, this should include the fact that `responseJSON` can be an
// array, but since we never actually use its array-ness, it makes the typing
@@ -21,20 +33,31 @@ export default class RequestError extends Error {
status?: number;
statusText?: string;
- constructor(method: string | undefined, path: string, options: ErrorOptionsObject) {
+ constructor(
+ method: 'POST' | 'GET' | 'DELETE' | 'PUT' | undefined,
+ path: string,
+ cause: Error,
+ responseMetadata?: ResponseMeta
+ ) {
+ const options = cause instanceof Error ? {cause} : {};
super(`${method || 'GET'} "${sanitizePath(path)}"`, options);
+ // TODO (kmclb) This is here to compensate for a bug in the SDK wherein it
+ // ignores subclassing of `Error` when getting error type. Once that's
+ // fixed, this can go.
this.name = 'RequestError';
- Object.setPrototypeOf(this, new.target.prototype);
+ this.addResponseMetadata(responseMetadata);
}
/**
* Updates Error with XHR response
*/
- setResponse(resp: ResponseMeta) {
+ addResponseMetadata(resp: ResponseMeta | undefined) {
if (resp) {
- this.setMessage(
- `${this.message} ${typeof resp.status === 'number' ? resp.status : 'n/a'}`
- );
+ this.setNameFromStatus(resp.status);
+
+ this.message = `${this.message} ${
+ typeof resp.status === 'number' ? resp.status : 'n/a'
+ }`;
// Some callback handlers expect these properties on the error object
if (resp.responseText) {
@@ -50,11 +73,11 @@ export default class RequestError extends Error {
}
}
- setMessage(message: string) {
- this.message = message;
- }
+ setNameFromStatus(status: number) {
+ const errorName = ERROR_MAP[status];
- setName(name: string) {
- this.name = name;
+ if (errorName) {
+ this.name = errorName;
+ }
}
}
|
2c97aba19b21753ab44714152f93691209f14c63
|
2025-01-14 21:35:26
|
Nar Saynorath
|
feat(dashboards): Add span extrapolation information to widgets (#83298)
| false
|
Add span extrapolation information to widgets (#83298)
|
feat
|
diff --git a/static/app/views/dashboards/widgetBuilder/components/widgetPreview.tsx b/static/app/views/dashboards/widgetBuilder/components/widgetPreview.tsx
index b917f1f7f34005..f8ba1f1dcefb56 100644
--- a/static/app/views/dashboards/widgetBuilder/components/widgetPreview.tsx
+++ b/static/app/views/dashboards/widgetBuilder/components/widgetPreview.tsx
@@ -7,6 +7,7 @@ import {
type DashboardDetails,
type DashboardFilters,
DisplayType,
+ WidgetType,
} from 'sentry/views/dashboards/types';
import {useWidgetBuilderContext} from 'sentry/views/dashboards/widgetBuilder/contexts/widgetBuilderContext';
import {convertBuilderStateToWidget} from 'sentry/views/dashboards/widgetBuilder/utils/convertBuilderStateToWidget';
@@ -81,6 +82,8 @@ function WidgetPreview({
// dashboard state to be added
onWidgetSplitDecision={() => {}}
// onWidgetSplitDecision={onWidgetSplitDecision}
+
+ showConfidenceWarning={widget.widgetType === WidgetType.SPANS}
/>
);
}
diff --git a/static/app/views/dashboards/widgetCard/chart.tsx b/static/app/views/dashboards/widgetCard/chart.tsx
index 15e1c41393b154..5d1c2b6117cabb 100644
--- a/static/app/views/dashboards/widgetCard/chart.tsx
+++ b/static/app/views/dashboards/widgetCard/chart.tsx
@@ -29,7 +29,7 @@ import type {
EChartEventHandler,
ReactEchartsRef,
} from 'sentry/types/echarts';
-import type {Organization} from 'sentry/types/organization';
+import type {Confidence, Organization} from 'sentry/types/organization';
import {defined} from 'sentry/utils';
import {
axisLabelFormatter,
@@ -51,6 +51,7 @@ import {
} from 'sentry/utils/discover/fields';
import getDynamicText from 'sentry/utils/getDynamicText';
import {eventViewFromWidget} from 'sentry/views/dashboards/utils';
+import ConfidenceWarning from 'sentry/views/dashboards/widgetCard/confidenceWarning';
import {getBucketSize} from 'sentry/views/dashboards/widgetCard/utils';
import WidgetLegendNameEncoderDecoder from 'sentry/views/dashboards/widgetLegendNameEncoderDecoder';
@@ -82,6 +83,7 @@ type WidgetCardChartProps = Pick<
widget: Widget;
widgetLegendState: WidgetLegendSelectionState;
chartGroup?: string;
+ confidence?: Confidence;
expandNumbers?: boolean;
isMobile?: boolean;
legendOptions?: LegendComponentOption;
@@ -93,6 +95,7 @@ type WidgetCardChartProps = Pick<
}>;
onZoom?: EChartDataZoomHandler;
shouldResize?: boolean;
+ showConfidenceWarning?: boolean;
timeseriesResultsTypes?: Record<string, AggregationOutputType>;
windowWidth?: number;
};
@@ -284,6 +287,8 @@ class WidgetCardChart extends Component<WidgetCardChartProps> {
noPadding,
timeseriesResultsTypes,
shouldResize,
+ confidence,
+ showConfidenceWarning,
} = this.props;
if (widget.displayType === 'table') {
@@ -527,19 +532,28 @@ class WidgetCardChart extends Component<WidgetCardChartProps> {
autoHeightResize={shouldResize ?? true}
noPadding={noPadding}
>
- {getDynamicText({
- value: this.chartComponent({
- ...zoomRenderProps,
- ...chartOptions,
- // Override default datazoom behaviour for updating Global Selection Header
- ...(onZoom ? {onDataZoom: onZoom} : {}),
- legend,
- series: [...series, ...(modifiedReleaseSeriesResults ?? [])],
- onLegendSelectChanged,
- forwardedRef,
- }),
- fixed: <Placeholder height="200px" testId="skeleton-ui" />,
- })}
+ <RenderedChartContainer>
+ {getDynamicText({
+ value: this.chartComponent({
+ ...zoomRenderProps,
+ ...chartOptions,
+ // Override default datazoom behaviour for updating Global Selection Header
+ ...(onZoom ? {onDataZoom: onZoom} : {}),
+ legend,
+ series: [...series, ...(modifiedReleaseSeriesResults ?? [])],
+ onLegendSelectChanged,
+ forwardedRef,
+ }),
+ fixed: <Placeholder height="200px" testId="skeleton-ui" />,
+ })}
+ </RenderedChartContainer>
+
+ {showConfidenceWarning && confidence && (
+ <ConfidenceWarning
+ query={widget.queries[0]?.conditions ?? ''}
+ confidence={confidence}
+ />
+ )}
</ChartWrapper>
</TransitionChart>
);
@@ -549,19 +563,27 @@ class WidgetCardChart extends Component<WidgetCardChartProps> {
<TransitionChart loading={loading} reloading={loading}>
<LoadingScreen loading={loading} />
<ChartWrapper autoHeightResize={shouldResize ?? true} noPadding={noPadding}>
- {getDynamicText({
- value: this.chartComponent({
- ...zoomRenderProps,
- ...chartOptions,
- // Override default datazoom behaviour for updating Global Selection Header
- ...(onZoom ? {onDataZoom: onZoom} : {}),
- legend,
- series,
- onLegendSelectChanged,
- forwardedRef,
- }),
- fixed: <Placeholder height="200px" testId="skeleton-ui" />,
- })}
+ <RenderedChartContainer>
+ {getDynamicText({
+ value: this.chartComponent({
+ ...zoomRenderProps,
+ ...chartOptions,
+ // Override default datazoom behaviour for updating Global Selection Header
+ ...(onZoom ? {onDataZoom: onZoom} : {}),
+ legend,
+ series,
+ onLegendSelectChanged,
+ forwardedRef,
+ }),
+ fixed: <Placeholder height="200px" testId="skeleton-ui" />,
+ })}
+ </RenderedChartContainer>
+ {showConfidenceWarning && confidence && (
+ <ConfidenceWarning
+ query={widget.queries[0]?.conditions ?? ''}
+ confidence={confidence}
+ />
+ )}
</ChartWrapper>
</TransitionChart>
);
@@ -623,6 +645,9 @@ const ChartWrapper = styled('div')<{autoHeightResize: boolean; noPadding?: boole
${p => p.autoHeightResize && 'height: 100%;'}
width: 100%;
padding: ${p => (p.noPadding ? `0` : `0 ${space(2)} ${space(2)}`)};
+ display: flex;
+ flex-direction: column;
+ gap: ${space(1)};
`;
const TableWrapper = styled('div')`
@@ -640,3 +665,7 @@ const StyledSimpleTableChart = styled(SimpleTableChart)`
const StyledErrorPanel = styled(ErrorPanel)`
padding: ${space(2)};
`;
+
+const RenderedChartContainer = styled('div')`
+ flex: 1;
+`;
diff --git a/static/app/views/dashboards/widgetCard/confidenceWarning.tsx b/static/app/views/dashboards/widgetCard/confidenceWarning.tsx
new file mode 100644
index 00000000000000..702de252cde29b
--- /dev/null
+++ b/static/app/views/dashboards/widgetCard/confidenceWarning.tsx
@@ -0,0 +1,23 @@
+import type {Confidence} from 'sentry/types/organization';
+import {DiscoverDatasets} from 'sentry/utils/discover/types';
+import {useExtrapolationMeta} from 'sentry/views/explore/charts';
+import {ConfidenceFooter} from 'sentry/views/explore/charts/confidenceFooter';
+
+interface ConfidenceWarningProps {
+ confidence: Confidence;
+ query: string;
+}
+
+export default function ConfidenceWarning({query, confidence}: ConfidenceWarningProps) {
+ const extrapolationMetaResults = useExtrapolationMeta({
+ dataset: DiscoverDatasets.SPANS_EAP_RPC,
+ query,
+ });
+
+ return (
+ <ConfidenceFooter
+ sampleCount={extrapolationMetaResults.data?.[0]?.['count_sample()']}
+ confidence={confidence}
+ />
+ );
+}
diff --git a/static/app/views/dashboards/widgetCard/genericWidgetQueries.tsx b/static/app/views/dashboards/widgetCard/genericWidgetQueries.tsx
index 93258931b48eb1..8ce6756a5bff84 100644
--- a/static/app/views/dashboards/widgetCard/genericWidgetQueries.tsx
+++ b/static/app/views/dashboards/widgetCard/genericWidgetQueries.tsx
@@ -8,7 +8,7 @@ import {isSelectionEqual} from 'sentry/components/organizations/pageFilters/util
import {t} from 'sentry/locale';
import type {PageFilters} from 'sentry/types/core';
import type {Series} from 'sentry/types/echarts';
-import type {Organization} from 'sentry/types/organization';
+import type {Confidence, Organization} from 'sentry/types/organization';
import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import type {AggregationOutputType} from 'sentry/utils/discover/fields';
import type {MEPState} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
@@ -43,6 +43,7 @@ export type OnDataFetchedProps = {
export type GenericWidgetQueriesChildrenProps = {
loading: boolean;
+ confidence?: Confidence;
errorMessage?: string;
pageLinks?: string;
tableResults?: TableDataWithTitle[];
diff --git a/static/app/views/dashboards/widgetCard/index.tsx b/static/app/views/dashboards/widgetCard/index.tsx
index 1ac418e75e5ba9..7bace56a76e652 100644
--- a/static/app/views/dashboards/widgetCard/index.tsx
+++ b/static/app/views/dashboards/widgetCard/index.tsx
@@ -86,6 +86,7 @@ type Props = WithRouterProps & {
onWidgetSplitDecision?: (splitDecision: WidgetType) => void;
renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
shouldResize?: boolean;
+ showConfidenceWarning?: boolean;
showContextMenu?: boolean;
showStoredAlert?: boolean;
tableItemLimit?: number;
@@ -131,6 +132,7 @@ function WidgetCard(props: Props) {
legendOptions,
widgetLegendState,
disableFullscreen,
+ showConfidenceWarning,
} = props;
if (widget.displayType === DisplayType.TOP_N) {
@@ -337,6 +339,7 @@ function WidgetCard(props: Props) {
onLegendSelectChanged={onLegendSelectChanged}
legendOptions={legendOptions}
widgetLegendState={widgetLegendState}
+ showConfidenceWarning={showConfidenceWarning}
/>
</WidgetFrame>
)}
diff --git a/static/app/views/dashboards/widgetCard/spansWidgetQueries.spec.tsx b/static/app/views/dashboards/widgetCard/spansWidgetQueries.spec.tsx
new file mode 100644
index 00000000000000..b767a96a6e497a
--- /dev/null
+++ b/static/app/views/dashboards/widgetCard/spansWidgetQueries.spec.tsx
@@ -0,0 +1,97 @@
+import {OrganizationFixture} from 'sentry-fixture/organization';
+import {PageFiltersFixture} from 'sentry-fixture/pageFilters';
+import {WidgetFixture} from 'sentry-fixture/widget';
+
+import {render, screen} from 'sentry-test/reactTestingLibrary';
+
+import SpansWidgetQueries from './spansWidgetQueries';
+
+describe('spansWidgetQueries', () => {
+ const api = new MockApiClient();
+ const organization = OrganizationFixture();
+ let widget = WidgetFixture();
+ const selection = PageFiltersFixture();
+
+ beforeEach(() => {
+ MockApiClient.clearMockResponses();
+ widget = WidgetFixture();
+ });
+
+ it('calculates the confidence for a single series', async () => {
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/events-stats/',
+ body: {
+ confidence: [
+ [1, [{count: 'low'}]],
+ [2, [{count: 'low'}]],
+ [3, [{count: 'low'}]],
+ ],
+ data: [],
+ },
+ });
+
+ render(
+ <SpansWidgetQueries
+ api={api}
+ organization={organization}
+ widget={widget}
+ selection={selection}
+ dashboardFilters={{}}
+ >
+ {({confidence}) => <div>{confidence}</div>}
+ </SpansWidgetQueries>
+ );
+
+ expect(await screen.findByText('low')).toBeInTheDocument();
+ });
+
+ it('calculates the confidence for a multi series', async () => {
+ widget = WidgetFixture({
+ queries: [
+ {
+ name: '',
+ aggregates: ['a', 'b'],
+ fields: ['a', 'b'],
+ columns: [],
+ conditions: '',
+ orderby: '',
+ },
+ ],
+ });
+ MockApiClient.addMockResponse({
+ url: '/organizations/org-slug/events-stats/',
+ body: {
+ a: {
+ confidence: [
+ [1, [{count: 'high'}]],
+ [2, [{count: 'high'}]],
+ [3, [{count: 'high'}]],
+ ],
+ data: [],
+ },
+ b: {
+ confidence: [
+ [1, [{count: 'high'}]],
+ [2, [{count: 'high'}]],
+ [3, [{count: 'high'}]],
+ ],
+ data: [],
+ },
+ },
+ });
+
+ render(
+ <SpansWidgetQueries
+ api={api}
+ organization={organization}
+ widget={widget}
+ selection={selection}
+ dashboardFilters={{}}
+ >
+ {({confidence}) => <div>{confidence}</div>}
+ </SpansWidgetQueries>
+ );
+
+ expect(await screen.findByText('high')).toBeInTheDocument();
+ });
+});
diff --git a/static/app/views/dashboards/widgetCard/spansWidgetQueries.tsx b/static/app/views/dashboards/widgetCard/spansWidgetQueries.tsx
new file mode 100644
index 00000000000000..082a0f04be0519
--- /dev/null
+++ b/static/app/views/dashboards/widgetCard/spansWidgetQueries.tsx
@@ -0,0 +1,98 @@
+import {useState} from 'react';
+
+import type {Client} from 'sentry/api';
+import {isMultiSeriesStats} from 'sentry/components/charts/utils';
+import type {PageFilters} from 'sentry/types/core';
+import type {
+ Confidence,
+ EventsStats,
+ MultiSeriesEventsStats,
+ Organization,
+} from 'sentry/types/organization';
+import {defined} from 'sentry/utils';
+import {dedupeArray} from 'sentry/utils/dedupeArray';
+import type {EventsTableData, TableData} from 'sentry/utils/discover/discoverQuery';
+import getDynamicText from 'sentry/utils/getDynamicText';
+import {determineSeriesConfidence} from 'sentry/views/alerts/rules/metric/utils/determineSeriesConfidence';
+import {SpansConfig} from 'sentry/views/dashboards/datasetConfig/spans';
+import {combineConfidenceForSeries} from 'sentry/views/explore/utils';
+import {transformToSeriesMap} from 'sentry/views/insights/common/queries/useSortedTimeSeries';
+
+import type {DashboardFilters, Widget} from '../types';
+
+import type {
+ GenericWidgetQueriesChildrenProps,
+ OnDataFetchedProps,
+} from './genericWidgetQueries';
+import GenericWidgetQueries from './genericWidgetQueries';
+
+type SeriesResult = EventsStats | MultiSeriesEventsStats;
+type TableResult = TableData | EventsTableData;
+
+type Props = {
+ api: Client;
+ children: (props: GenericWidgetQueriesChildrenProps) => JSX.Element;
+ organization: Organization;
+ selection: PageFilters;
+ widget: Widget;
+ cursor?: string;
+ dashboardFilters?: DashboardFilters;
+ limit?: number;
+ onDataFetched?: (results: OnDataFetchedProps) => void;
+};
+
+function SpansWidgetQueries({
+ children,
+ api,
+ organization,
+ selection,
+ widget,
+ cursor,
+ limit,
+ dashboardFilters,
+ onDataFetched,
+}: Props) {
+ const config = SpansConfig;
+
+ const [confidence, setConfidence] = useState<Confidence | null>(null);
+
+ const afterFetchSeriesData = (result: SeriesResult) => {
+ if (isMultiSeriesStats(result)) {
+ const dedupedYAxes = dedupeArray(widget.queries[0]?.aggregates ?? []);
+ const seriesMap = transformToSeriesMap(result, dedupedYAxes);
+ const series = dedupedYAxes.flatMap(yAxis => seriesMap[yAxis]).filter(defined);
+ const seriesConfidence = combineConfidenceForSeries(series);
+ setConfidence(seriesConfidence);
+ } else {
+ const seriesConfidence = determineSeriesConfidence(result);
+ setConfidence(seriesConfidence);
+ }
+ };
+
+ return getDynamicText({
+ value: (
+ <GenericWidgetQueries<SeriesResult, TableResult>
+ config={config}
+ api={api}
+ organization={organization}
+ selection={selection}
+ widget={widget}
+ cursor={cursor}
+ limit={limit}
+ dashboardFilters={dashboardFilters}
+ onDataFetched={onDataFetched}
+ afterFetchSeriesData={afterFetchSeriesData}
+ >
+ {props =>
+ children({
+ ...props,
+ confidence,
+ })
+ }
+ </GenericWidgetQueries>
+ ),
+ fixed: <div />,
+ });
+}
+
+export default SpansWidgetQueries;
diff --git a/static/app/views/dashboards/widgetCard/widgetCardChartContainer.tsx b/static/app/views/dashboards/widgetCard/widgetCardChartContainer.tsx
index fc0c1e62541f04..30b385e69b8af6 100644
--- a/static/app/views/dashboards/widgetCard/widgetCardChartContainer.tsx
+++ b/static/app/views/dashboards/widgetCard/widgetCardChartContainer.tsx
@@ -55,6 +55,7 @@ type Props = {
onZoom?: EChartDataZoomHandler;
renderErrorMessage?: (errorMessage?: string) => React.ReactNode;
shouldResize?: boolean;
+ showConfidenceWarning?: boolean;
tableItemLimit?: number;
windowWidth?: number;
};
@@ -78,6 +79,7 @@ export function WidgetCardChartContainer({
chartGroup,
shouldResize,
widgetLegendState,
+ showConfidenceWarning,
}: Props) {
const location = useLocation();
@@ -105,6 +107,7 @@ export function WidgetCardChartContainer({
errorMessage,
loading,
timeseriesResultsTypes,
+ confidence,
}) => {
if (widget.widgetType === WidgetType.ISSUE) {
return (
@@ -160,6 +163,8 @@ export function WidgetCardChartContainer({
: {selected: widgetLegendState.getWidgetSelectionState(widget)}
}
widgetLegendState={widgetLegendState}
+ showConfidenceWarning={showConfidenceWarning}
+ confidence={confidence}
/>
</Fragment>
);
diff --git a/static/app/views/dashboards/widgetCard/widgetCardDataLoader.tsx b/static/app/views/dashboards/widgetCard/widgetCardDataLoader.tsx
index b133f261b4e4c6..30e0236eeb34d3 100644
--- a/static/app/views/dashboards/widgetCard/widgetCardDataLoader.tsx
+++ b/static/app/views/dashboards/widgetCard/widgetCardDataLoader.tsx
@@ -2,10 +2,12 @@ import {Fragment} from 'react';
import type {PageFilters} from 'sentry/types/core';
import type {Series} from 'sentry/types/echarts';
+import type {Confidence} from 'sentry/types/organization';
import type {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
import type {AggregationOutputType} from 'sentry/utils/discover/fields';
import useApi from 'sentry/utils/useApi';
import useOrganization from 'sentry/utils/useOrganization';
+import SpansWidgetQueries from 'sentry/views/dashboards/widgetCard/spansWidgetQueries';
import type {DashboardFilters, Widget} from '../types';
import {WidgetType} from '../types';
@@ -16,6 +18,7 @@ import WidgetQueries from './widgetQueries';
type Results = {
loading: boolean;
+ confidence?: Confidence;
errorMessage?: string;
pageLinks?: string;
tableResults?: TableDataWithTitle[];
@@ -93,6 +96,22 @@ export function WidgetCardDataLoader({
);
}
+ if (widget.widgetType === WidgetType.SPANS) {
+ return (
+ <SpansWidgetQueries
+ api={api}
+ organization={organization}
+ widget={widget}
+ selection={selection}
+ limit={tableItemLimit}
+ onDataFetched={onDataFetched}
+ dashboardFilters={dashboardFilters}
+ >
+ {props => <Fragment>{children({...props})}</Fragment>}
+ </SpansWidgetQueries>
+ );
+ }
+
return (
<WidgetQueries
api={api}
@@ -110,6 +129,7 @@ export function WidgetCardDataLoader({
errorMessage,
loading,
timeseriesResultsTypes,
+ confidence,
}) => (
<Fragment>
{children({
@@ -118,6 +138,7 @@ export function WidgetCardDataLoader({
errorMessage,
loading,
timeseriesResultsTypes,
+ confidence,
})}
</Fragment>
)}
diff --git a/static/app/views/explore/charts/index.tsx b/static/app/views/explore/charts/index.tsx
index 76128eb68be25a..06be70b04d08d4 100644
--- a/static/app/views/explore/charts/index.tsx
+++ b/static/app/views/explore/charts/index.tsx
@@ -268,7 +268,7 @@ export function ExploreCharts({
);
}
-function useExtrapolationMeta({
+export function useExtrapolationMeta({
dataset,
query,
}: {
diff --git a/static/app/views/insights/common/queries/useSortedTimeSeries.tsx b/static/app/views/insights/common/queries/useSortedTimeSeries.tsx
index 872ff93328adb9..0997223e375161 100644
--- a/static/app/views/insights/common/queries/useSortedTimeSeries.tsx
+++ b/static/app/views/insights/common/queries/useSortedTimeSeries.tsx
@@ -135,7 +135,7 @@ function isMultiSeriesEventsStats(
return Object.values(obj).every(series => isEventsStats(series));
}
-function transformToSeriesMap(
+export function transformToSeriesMap(
result: MultiSeriesEventsStats | GroupedMultiSeriesEventsStats | undefined,
yAxis: string[]
): SeriesMap {
|
2aed97c59680bf9d09df900ac65c0584363f76c1
|
2017-12-06 00:38:47
|
Lauryn Brown
|
feat(api): Search related events by event ID (#6688)
| false
|
Search related events by event ID (#6688)
|
feat
|
diff --git a/src/sentry/api/endpoints/group_events.py b/src/sentry/api/endpoints/group_events.py
index 9f22a2f0ec8f2c..7b53aa9deb4a48 100644
--- a/src/sentry/api/endpoints/group_events.py
+++ b/src/sentry/api/endpoints/group_events.py
@@ -12,6 +12,7 @@
from sentry.utils.apidocs import scenario, attach_scenarios
from rest_framework.response import Response
from sentry.search.utils import InvalidQuery
+from django.db.models import Q
@scenario('ListAvailableSamples')
@@ -40,6 +41,7 @@ def get(self, request, group):
)
query = request.GET.get('query')
+
if query:
try:
query_kwargs = parse_query(group.project, query, request.user)
@@ -47,9 +49,12 @@ def get(self, request, group):
return Response({'detail': six.text_type(exc)}, status=400)
if query_kwargs['query']:
- events = events.filter(
- message__icontains=query_kwargs['query'],
- )
+ q = Q(message__icontains=query_kwargs['query'])
+
+ if len(query) == 32:
+ q |= Q(event_id__exact=query_kwargs['query'])
+
+ events = events.filter(q)
if query_kwargs['tags']:
try:
diff --git a/tests/sentry/api/endpoints/test_group_events.py b/tests/sentry/api/endpoints/test_group_events.py
index da42d5000f06dc..846f47c4b34151 100644
--- a/tests/sentry/api/endpoints/test_group_events.py
+++ b/tests/sentry/api/endpoints/test_group_events.py
@@ -120,3 +120,51 @@ def test_tags(self):
assert response.status_code == 200, response.content
assert len(response.data) == 0
+
+ def test_search_event_by_id(self):
+ self.login_as(user=self.user)
+
+ group = self.create_group()
+ event_1 = self.create_event('a' * 32, group=group)
+ self.create_event('b' * 32, group=group)
+ query = event_1.event_id
+
+ url = '/api/0/issues/{}/events/?query={}'.format(group.id, query)
+ response = self.client.get(url, format='json')
+
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 1
+ assert response.data[0]['eventID'] == event_1.event_id
+
+ def test_search_event_by_message(self):
+ self.login_as(user=self.user)
+
+ group = self.create_group()
+ event_1 = self.create_event(event_id='a' * 32, group=group, message="foo bar hello world")
+
+ event_2 = self.create_event(event_id='b' * 32, group=group, message='this bar hello world ')
+
+ query_1 = "foo"
+ query_2 = "hello+world"
+
+ # Single Word Query
+ url = '/api/0/issues/{}/events/?query={}'.format(group.id, query_1)
+ response = self.client.get(url, format='json')
+
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 1
+ assert response.data[0]['id'] == six.text_type(
+ event_1.id) and response.data[0]['eventID'] == event_1.event_id
+
+ # Multiple Word Query
+ url = '/api/0/issues/{}/events/?query={}'.format(group.id, query_2)
+ response = self.client.get(url, format='json')
+
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 2
+ assert sorted(map(lambda x: x['id'], response.data)) == sorted(
+ [
+ six.text_type(event_1.id),
+ six.text_type(event_2.id),
+ ]
+ )
|
fb0b09ae58f176f4db3fb96a50923944691bd3af
|
2019-04-05 03:07:55
|
Katie Byers
|
fix(filters): Filter out google spiders explicitly (#12611)
| false
|
Filter out google spiders explicitly (#12611)
|
fix
|
diff --git a/src/sentry/filters/web_crawlers.py b/src/sentry/filters/web_crawlers.py
index a6ad3b5961433c..870027fad2e42b 100644
--- a/src/sentry/filters/web_crawlers.py
+++ b/src/sentry/filters/web_crawlers.py
@@ -12,12 +12,12 @@
CRAWLERS = re.compile(
r'|'.join(
(
- # various Google services
- r'AdsBot',
- # Google Adsense
- r'Mediapartners',
- # Google+ and Google web search, but not apis-google
- r'(?<!APIs-)Google',
+ # Google spiders (Adsense and others)
+ # https://support.google.com/webmasters/answer/1061943?hl=en
+ r'Mediapartners\-Google',
+ r'AdsBot\-Google',
+ r'Googlebot',
+ r'FeedFetcher\-Google',
# Bing search
r'BingBot',
r'BingPreview',
diff --git a/tests/sentry/filters/test_web_crawlers.py b/tests/sentry/filters/test_web_crawlers.py
index baca9958c966ec..d7e467956c7f36 100644
--- a/tests/sentry/filters/test_web_crawlers.py
+++ b/tests/sentry/filters/test_web_crawlers.py
@@ -23,10 +23,28 @@ def get_mock_data(self, user_agent):
}
}
- def test_filters_googlebot(self):
- data = self.get_mock_data('Googlebot')
+ def test_filters_google_adsense(self):
+ data = self.get_mock_data('Mediapartners-Google')
assert self.apply_filter(data)
+ def test_filters_google_adsbot(self):
+ data = self.get_mock_data('AdsBot-Google (+http://www.google.com/adsbot.html)')
+ assert self.apply_filter(data)
+
+ def test_filters_google_bot(self):
+ data = self.get_mock_data(
+ 'Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)')
+ assert self.apply_filter(data)
+
+ def test_filters_google_feedfetcher(self):
+ data = self.get_mock_data('FeedFetcher-Google; (+http://www.google.com/feedfetcher.html)')
+ assert self.apply_filter(data)
+
+ def test_does_not_filter_google_pubsub(self):
+ data = self.get_mock_data(
+ 'APIs-Google (+https://developers.google.com/webmasters/APIs-Google.html)')
+ assert not self.apply_filter(data)
+
def test_does_not_filter_chrome(self):
data = self.get_mock_data(
'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
|
b5c5a98bc5bc2d860685f9fe07af7286d5ab5799
|
2021-09-27 21:26:02
|
edwardgou-sentry
|
fix(dashboards): Fixed add widget from discover to new dashboard not creating widget (#28827)
| false
|
Fixed add widget from discover to new dashboard not creating widget (#28827)
|
fix
|
diff --git a/static/app/views/dashboardsV2/create.tsx b/static/app/views/dashboardsV2/create.tsx
index e4f130046910ca..033d4e6916ca92 100644
--- a/static/app/views/dashboardsV2/create.tsx
+++ b/static/app/views/dashboardsV2/create.tsx
@@ -1,4 +1,4 @@
-import React from 'react';
+import React, {useEffect, useState} from 'react';
import {browserHistory, RouteComponentProps} from 'react-router';
import Feature from 'app/components/acl/feature';
@@ -10,7 +10,7 @@ import withOrganization from 'app/utils/withOrganization';
import {EMPTY_DASHBOARD} from './data';
import DashboardDetail from './detail';
-import {DashboardState} from './types';
+import {DashboardState, Widget} from './types';
import {cloneDashboard, constructWidgetFromQuery} from './utils';
type Props = RouteComponentProps<{orgId: string}, {}> & {
@@ -19,7 +19,8 @@ type Props = RouteComponentProps<{orgId: string}, {}> & {
};
function CreateDashboard(props: Props) {
- const {location} = props;
+ const {organization, location} = props;
+ const [newWidget, setNewWidget] = useState<Widget | undefined>();
function renderDisabled() {
return (
<PageContent>
@@ -29,10 +30,13 @@ function CreateDashboard(props: Props) {
}
const dashboard = cloneDashboard(EMPTY_DASHBOARD);
- const newWidget = constructWidgetFromQuery(location.query);
- if (newWidget) {
- browserHistory.replace(location.pathname);
- }
+ useEffect(() => {
+ const constructedWidget = constructWidgetFromQuery(location.query);
+ setNewWidget(constructedWidget);
+ if (constructedWidget) {
+ browserHistory.replace(location.pathname);
+ }
+ }, [organization.slug]);
return (
<Feature
features={['dashboards-edit']}
diff --git a/static/app/views/dashboardsV2/dashboard.tsx b/static/app/views/dashboardsV2/dashboard.tsx
index 82a5258cce5c2e..a385a95a03c563 100644
--- a/static/app/views/dashboardsV2/dashboard.tsx
+++ b/static/app/views/dashboardsV2/dashboard.tsx
@@ -39,11 +39,29 @@ type Props = {
class Dashboard extends Component<Props> {
async componentDidMount() {
- const {api, organization, isEditing, newWidget} = this.props;
+ const {isEditing} = this.props;
// Load organization tags when in edit mode.
if (isEditing) {
this.fetchTags();
}
+ this.addNewWidget();
+ }
+
+ async componentDidUpdate(prevProps: Props) {
+ const {isEditing, newWidget} = this.props;
+
+ // Load organization tags when going into edit mode.
+ // We use tags on the add widget modal.
+ if (prevProps.isEditing !== isEditing && isEditing) {
+ this.fetchTags();
+ }
+ if (newWidget !== prevProps.newWidget) {
+ this.addNewWidget();
+ }
+ }
+
+ async addNewWidget() {
+ const {api, organization, newWidget} = this.props;
if (newWidget) {
try {
await validateWidget(api, organization.slug, newWidget);
@@ -55,16 +73,6 @@ class Dashboard extends Component<Props> {
}
}
- componentDidUpdate(prevProps: Props) {
- const {isEditing} = this.props;
-
- // Load organization tags when going into edit mode.
- // We use tags on the add widget modal.
- if (prevProps.isEditing !== isEditing && isEditing) {
- this.fetchTags();
- }
- }
-
fetchTags() {
const {api, organization, selection} = this.props;
loadOrganizationTags(api, organization.slug, selection);
diff --git a/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
new file mode 100644
index 00000000000000..83e5db513c9d61
--- /dev/null
+++ b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
@@ -0,0 +1,87 @@
+import {mountWithTheme} from 'sentry-test/enzyme';
+import {initializeOrg} from 'sentry-test/initializeOrg';
+
+import Dashboard from 'app/views/dashboardsV2/dashboard';
+import {DisplayType} from 'app/views/dashboardsV2/types';
+
+describe('Dashboards > Dashboard', () => {
+ // @ts-expect-error
+ const organization = TestStubs.Organization({
+ features: ['dashboards-basic', 'dashboards-edit'],
+ });
+ const mockDashboard = {
+ dateCreated: '2021-08-10T21:20:46.798237Z',
+ id: '1',
+ title: 'Test Dashboard',
+ widgets: [],
+ };
+ const newWidget = {
+ title: 'Test Query',
+ displayType: DisplayType.LINE,
+ interval: '5m',
+ queries: [
+ {
+ name: '',
+ conditions: '',
+ fields: ['count()'],
+ orderby: '',
+ },
+ ],
+ };
+
+ let initialData;
+
+ beforeEach(() => {
+ initialData = initializeOrg({organization, router: {}, project: 1, projects: []});
+ // @ts-expect-error
+ MockApiClient.addMockResponse({
+ url: `/organizations/org-slug/dashboards/widgets/`,
+ method: 'POST',
+ body: [],
+ });
+ });
+ it('dashboard adds new widget if component is mounted with newWidget prop', async () => {
+ const mock = jest.fn();
+ const wrapper = mountWithTheme(
+ <Dashboard
+ paramDashboardId="1"
+ dashboard={mockDashboard}
+ organization={initialData.organization}
+ isEditing={false}
+ onUpdate={mock}
+ onSetWidgetToBeUpdated={() => undefined}
+ router={initialData.router}
+ location={initialData.location}
+ newWidget={newWidget}
+ />,
+ initialData.routerContext
+ );
+ // @ts-expect-error
+ await tick();
+ wrapper.update();
+ expect(mock).toHaveBeenCalled();
+ });
+
+ it('dashboard adds new widget if component updated with newWidget prop', async () => {
+ const mock = jest.fn();
+ const wrapper = mountWithTheme(
+ <Dashboard
+ paramDashboardId="1"
+ dashboard={mockDashboard}
+ organization={initialData.organization}
+ isEditing={false}
+ onUpdate={mock}
+ onSetWidgetToBeUpdated={() => undefined}
+ router={initialData.router}
+ location={initialData.location}
+ />,
+ initialData.routerContext
+ );
+ expect(mock).not.toHaveBeenCalled();
+ wrapper.setProps({newWidget});
+ // @ts-expect-error
+ await tick();
+ wrapper.update();
+ expect(mock).toHaveBeenCalled();
+ });
+});
|
523817aac253613928339daadbe1693b4928060d
|
2021-03-11 23:53:43
|
William Mak
|
ref(trace-view): Some minor changes to the endpoint (#24390)
| false
|
Some minor changes to the endpoint (#24390)
|
ref
|
diff --git a/src/sentry/api/endpoints/organization_events_trace.py b/src/sentry/api/endpoints/organization_events_trace.py
index adbab09607faa6..017736b653013e 100644
--- a/src/sentry/api/endpoints/organization_events_trace.py
+++ b/src/sentry/api/endpoints/organization_events_trace.py
@@ -35,6 +35,7 @@ def serialize_event(self, event, parent, generation=None):
"span_id": event["trace.span"],
"transaction": event["transaction"],
"transaction.duration": event["transaction.duration"],
+ "transaction.op": event["transaction.op"],
"project_id": event["project.id"],
"project_slug": event["project"],
"parent_event_id": parent,
@@ -55,10 +56,12 @@ def get(self, request, organization, trace_id):
with self.handle_query_errors():
result = discover.query(
+ # selected_columns is a set list, since we only want to include the minimum to render the trace
selected_columns=[
"id",
"timestamp",
"transaction.duration",
+ "transaction.op",
"transaction",
# project gets the slug, and project.id gets added automatically
"project",
@@ -182,8 +185,8 @@ def get_error_map(self, organization, trace_id, params):
error_results = discover.query(
selected_columns=[
"id",
+ "project",
"timestamp",
- "issue",
"trace.span",
],
orderby=["-timestamp", "id"],
@@ -198,17 +201,18 @@ def get_error_map(self, organization, trace_id, params):
# Use issue ids to get the error's short id
error_map = defaultdict(list)
if error_results["data"]:
- self.handle_issues(error_results["data"], params["project_id"], organization)
for row in error_results["data"]:
- error_map[row["trace.span"]].append(
- {
- "issue": row["issue"],
- "id": row["id"],
- "span": row["trace.span"],
- }
- )
+ error_map[row["trace.span"]].append(self.serialize_error(row))
return error_map
+ def serialize_error(self, event):
+ return {
+ "event_id": event["id"],
+ "span": event["trace.span"],
+ "project_id": event["project.id"],
+ "project_slug": event["project"],
+ }
+
def serialize_event(self, *args, **kwargs):
event = super().serialize_event(*args, **kwargs)
event.update(
diff --git a/tests/snuba/api/endpoints/test_organization_events_trace.py b/tests/snuba/api/endpoints/test_organization_events_trace.py
index f47ca672c37b14..c701c8be2b4594 100644
--- a/tests/snuba/api/endpoints/test_organization_events_trace.py
+++ b/tests/snuba/api/endpoints/test_organization_events_trace.py
@@ -575,14 +575,16 @@ def test_with_errors(self):
gen1_event = response.data["children"][0]
assert len(gen1_event["errors"]) == 2
assert {
- "id": error.event_id,
- "issue": error.group.qualified_short_id,
+ "event_id": error.event_id,
"span": self.gen1_span_ids[0],
+ "project_id": self.gen1_project.id,
+ "project_slug": self.gen1_project.slug,
} in gen1_event["errors"]
assert {
- "id": error1.event_id,
- "issue": error1.group.qualified_short_id,
+ "event_id": error1.event_id,
"span": self.gen1_span_ids[0],
+ "project_id": self.gen1_project.id,
+ "project_slug": self.gen1_project.slug,
} in gen1_event["errors"]
def test_with_default(self):
@@ -612,7 +614,8 @@ def test_with_default(self):
root_event = response.data
assert len(root_event["errors"]) == 1
assert {
- "id": default_event.event_id,
- "issue": default_event.group.qualified_short_id,
+ "event_id": default_event.event_id,
"span": self.root_span_ids[0],
+ "project_id": self.gen1_project.id,
+ "project_slug": self.gen1_project.slug,
} in root_event["errors"]
|
33572157a4b3f90baa9c2a5769ccb92163c51d8d
|
2022-01-06 01:47:56
|
Scott Cooper
|
fix(teamStats): Round metric alerts triggered average (#30916)
| false
|
Round metric alerts triggered average (#30916)
|
fix
|
diff --git a/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx b/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx
index 78b2049efe5d61..ba41932db1390e 100644
--- a/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx
+++ b/static/app/views/organizationStats/teamInsights/teamAlertsTriggered.tsx
@@ -1,6 +1,7 @@
import {Fragment} from 'react';
import {css} from '@emotion/react';
import styled from '@emotion/styled';
+import round from 'lodash/round';
import AsyncComponent from 'sentry/components/asyncComponent';
import Button from 'sentry/components/button';
@@ -178,27 +179,26 @@ class TeamAlertsTriggered extends AsyncComponent<Props, State> {
<AlignRight key="diff">{t('Difference')}</AlignRight>,
]}
>
- {alertsTriggeredRules &&
- alertsTriggeredRules.map(rule => (
- <Fragment key={rule.id}>
- <div>
- <Link
- to={`/organizations/${organization.id}/alerts/rules/details/${rule.id}/`}
- >
- {rule.name}
- </Link>
- </div>
- <ProjectBadgeContainer>
- <ProjectBadge
- avatarSize={18}
- project={projects.find(p => p.slug === rule.projects[0])}
- />
- </ProjectBadgeContainer>
- <AlignRight>{rule.weeklyAvg}</AlignRight>
- <AlignRight>{rule.totalThisWeek}</AlignRight>
- <AlignRight>{this.renderTrend(rule)}</AlignRight>
- </Fragment>
- ))}
+ {alertsTriggeredRules?.map(rule => (
+ <Fragment key={rule.id}>
+ <div>
+ <Link
+ to={`/organizations/${organization.id}/alerts/rules/details/${rule.id}/`}
+ >
+ {rule.name}
+ </Link>
+ </div>
+ <ProjectBadgeContainer>
+ <ProjectBadge
+ avatarSize={18}
+ project={projects.find(p => p.slug === rule.projects[0])}
+ />
+ </ProjectBadgeContainer>
+ <AlignRight>{round(rule.weeklyAvg, 2)}</AlignRight>
+ <AlignRight>{rule.totalThisWeek}</AlignRight>
+ <AlignRight>{this.renderTrend(rule)}</AlignRight>
+ </Fragment>
+ ))}
</StyledPanelTable>
</Fragment>
);
|
493d58fa32ab30a8bd860d20811f1ba71c9f1188
|
2023-02-22 14:50:45
|
Evan Purkhiser
|
fix(js): Use named export for charts tooltip (#43373)
| false
|
Use named export for charts tooltip (#43373)
|
fix
|
diff --git a/static/app/components/charts/baseChart.tsx b/static/app/components/charts/baseChart.tsx
index 5a90e6f346fe3f..49c1811eb339da 100644
--- a/static/app/components/charts/baseChart.tsx
+++ b/static/app/components/charts/baseChart.tsx
@@ -46,7 +46,7 @@ import {defined} from 'sentry/utils';
import Grid from './components/grid';
import Legend from './components/legend';
-import Tooltip, {TooltipSubLabel} from './components/tooltip';
+import {ChartTooltip, TooltipSubLabel} from './components/tooltip';
import XAxis from './components/xAxis';
import YAxis from './components/yAxis';
import LineSeries from './series/lineSeries';
@@ -476,7 +476,7 @@ function BaseChartUnwrapped({
const tooltipOrNone =
tooltip !== null
- ? Tooltip({
+ ? ChartTooltip({
showTimeInTooltip,
isGroupedByDate,
addSecondsToTimeFormat,
diff --git a/static/app/components/charts/components/tooltip.tsx b/static/app/components/charts/components/tooltip.tsx
index d3a77a20f4b331..0c98b33242a35f 100644
--- a/static/app/components/charts/components/tooltip.tsx
+++ b/static/app/components/charts/components/tooltip.tsx
@@ -295,7 +295,7 @@ type Props = ChartProps['tooltip'] &
chartId?: string;
};
-export default function Tooltip({
+export function ChartTooltip({
filter,
isGroupedByDate,
showTimeInTooltip,
@@ -402,3 +402,6 @@ export default function Tooltip({
...props,
};
}
+
+const DoNotUseChartTooltip = ChartTooltip;
+export default DoNotUseChartTooltip;
diff --git a/static/app/views/replays/detail/memoryChart.tsx b/static/app/views/replays/detail/memoryChart.tsx
index e8e67046c8950b..45b74adb130b8e 100644
--- a/static/app/views/replays/detail/memoryChart.tsx
+++ b/static/app/views/replays/detail/memoryChart.tsx
@@ -5,7 +5,7 @@ import moment from 'moment';
import {AreaChart, AreaChartProps} from 'sentry/components/charts/areaChart';
import Grid from 'sentry/components/charts/components/grid';
-import Tooltip from 'sentry/components/charts/components/tooltip';
+import {ChartTooltip} from 'sentry/components/charts/components/tooltip';
import XAxis from 'sentry/components/charts/components/xAxis';
import YAxis from 'sentry/components/charts/components/yAxis';
import EmptyMessage from 'sentry/components/emptyMessage';
@@ -68,7 +68,7 @@ function MemoryChart({
left: space(1),
right: space(1),
}),
- tooltip: Tooltip({
+ tooltip: ChartTooltip({
appendToBody: true,
trigger: 'axis',
renderMode: 'html',
|
e1c7ff7ce5ddd5075bb47e132ac3b022650174e0
|
2023-04-28 23:31:21
|
Snigdha Sharma
|
feat(issue-states): Add untilEscalating info to status details (#48164)
| false
|
Add untilEscalating info to status details (#48164)
|
feat
|
diff --git a/src/sentry/api/helpers/group_index/update.py b/src/sentry/api/helpers/group_index/update.py
index 84ea26c971bfd3..810a0446b7b127 100644
--- a/src/sentry/api/helpers/group_index/update.py
+++ b/src/sentry/api/helpers/group_index/update.py
@@ -548,7 +548,7 @@ def update_groups(
GroupResolution.objects.filter(group__in=group_ids).delete()
if new_status == GroupStatus.IGNORED:
if new_substatus == GroupSubStatus.UNTIL_ESCALATING and has_escalating_issues:
- handle_archived_until_escalating(
+ result["statusDetails"] = handle_archived_until_escalating(
group_list, acting_user, projects, sender=update_groups
)
else:
diff --git a/src/sentry/issues/ignored.py b/src/sentry/issues/ignored.py
index 09842c3a2b0827..deb8ac6b5456da 100644
--- a/src/sentry/issues/ignored.py
+++ b/src/sentry/issues/ignored.py
@@ -37,7 +37,7 @@ def handle_archived_until_escalating(
acting_user: User | None,
projects: Sequence[Project],
sender: Any,
-) -> None:
+) -> Dict[str, bool]:
"""
Handle issues that are archived until escalating and create a forecast for them.
@@ -70,7 +70,7 @@ def handle_archived_until_escalating(
sender=sender,
)
- return
+ return {"ignoreUntilEscalating": True}
def handle_ignored(
diff --git a/src/sentry/issues/status_change.py b/src/sentry/issues/status_change.py
index 445d058fc0247a..dd69f93f5817b5 100644
--- a/src/sentry/issues/status_change.py
+++ b/src/sentry/issues/status_change.py
@@ -72,6 +72,7 @@ def handle_status_update(
"ignoreUserCount": status_details.get("ignoreUserCount", None),
"ignoreUserWindow": status_details.get("ignoreUserWindow", None),
"ignoreWindow": status_details.get("ignoreWindow", None),
+ "ignoreUntilEscalating": status_details.get("ignoreUntilEscalating", None),
}
if activity_data["ignoreUntil"] is not None:
activity_data["ignoreUntil"] = json.datetime_to_str(activity_data["ignoreUntil"])
diff --git a/tests/sentry/issues/test_ignored.py b/tests/sentry/issues/test_ignored.py
index b2fef6ac354ddd..8602c4742fd7dc 100644
--- a/tests/sentry/issues/test_ignored.py
+++ b/tests/sentry/issues/test_ignored.py
@@ -65,10 +65,13 @@ def test_archive_until_escalating_no_counts(
group=self.group, reason=GroupInboxReason.NEW.value
).exists()
- handle_archived_until_escalating([self.group], self.user, [self.project], sender=self)
+ status_details = handle_archived_until_escalating(
+ [self.group], self.user, [self.project], sender=self
+ )
assert not GroupInbox.objects.filter(group=self.group).exists()
# Make sure we don't create a snooze for until_escalating
assert not GroupSnooze.objects.filter(group=self.group).exists()
+ assert status_details == {"ignoreUntilEscalating": True}
fetched_forecast = EscalatingGroupForecast.fetch(self.group.project.id, self.group.id)
assert fetched_forecast is not None
@@ -91,10 +94,13 @@ def test_archive_until_escalating_with_counts(
group=self.group, reason=GroupInboxReason.NEW.value
).exists()
- handle_archived_until_escalating([self.group], self.user, [self.project], sender=self)
+ status_details = handle_archived_until_escalating(
+ [self.group], self.user, [self.project], sender=self
+ )
assert not GroupInbox.objects.filter(group=self.group).exists()
# Make sure we don't create a snooze for until_escalating
assert not GroupSnooze.objects.filter(group=self.group).exists()
+ assert status_details == {"ignoreUntilEscalating": True}
fetched_forecast = EscalatingGroupForecast.fetch(self.group.project.id, self.group.id)
assert fetched_forecast is not None
@@ -113,5 +119,8 @@ def test_archive_until_escalating_analytics(
group=self.group, reason=GroupInboxReason.NEW.value
).exists()
- handle_archived_until_escalating([self.group], self.user, [self.project], sender=self)
+ status_details = handle_archived_until_escalating(
+ [self.group], self.user, [self.project], sender=self
+ )
assert mock_send_robust.called
+ assert status_details == {"ignoreUntilEscalating": True}
diff --git a/tests/sentry/issues/test_status_change.py b/tests/sentry/issues/test_status_change.py
index 877ffab0f8381d..69264f82f889cf 100644
--- a/tests/sentry/issues/test_status_change.py
+++ b/tests/sentry/issues/test_status_change.py
@@ -94,3 +94,29 @@ def test_ignore_new_issue(self, issue_ignored: Any) -> None:
assert GroupHistory.objects.filter(
group=self.group, status=GroupHistoryStatus.IGNORED
).exists()
+
+ @patch("sentry.signals.issue_ignored.send_robust")
+ def test_ignore_until_escalating(self, issue_ignored: Any) -> None:
+ self.create_issue(GroupStatus.UNRESOLVED)
+ handle_status_update(
+ self.group_list,
+ self.projects,
+ self.project_lookup,
+ acting_user=self.user,
+ new_status=GroupStatus.IGNORED,
+ new_substatus=None,
+ is_bulk=True,
+ status_details={"ignoreUntilEscalating": True},
+ sender=self,
+ activity_type=None,
+ )
+
+ assert issue_ignored.called
+ activity = Activity.objects.filter(
+ group=self.group, type=ActivityType.SET_IGNORED.value
+ ).first()
+ assert activity.data.get("ignoreUntilEscalating")
+
+ assert GroupHistory.objects.filter(
+ group=self.group, status=GroupHistoryStatus.IGNORED
+ ).exists()
|
b09714469b948b907902d3db7b1a532ed304d692
|
2023-01-20 03:37:42
|
Snigdha Sharma
|
feat(codecov): Change codecovAccess setting text (#43404)
| false
|
Change codecovAccess setting text (#43404)
|
feat
|
diff --git a/static/app/views/settings/organizationGeneralSettings/index.spec.tsx b/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
index 28713b7e4cdef2..3b364f2a5dd9b3 100644
--- a/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
+++ b/static/app/views/settings/organizationGeneralSettings/index.spec.tsx
@@ -68,7 +68,9 @@ describe('OrganizationGeneralSettings', function () {
method: 'PUT',
});
- userEvent.click(screen.getByRole('checkbox', {name: /codecov access/i}));
+ userEvent.click(
+ screen.getByRole('checkbox', {name: /Enable Code Coverage Insights/i})
+ );
await waitFor(() => {
expect(mock).toHaveBeenCalledWith(
diff --git a/static/app/views/settings/organizationGeneralSettings/organizationSettingsForm.tsx b/static/app/views/settings/organizationGeneralSettings/organizationSettingsForm.tsx
index f8f5bd76ec5c80..44a17820609a95 100644
--- a/static/app/views/settings/organizationGeneralSettings/organizationSettingsForm.tsx
+++ b/static/app/views/settings/organizationGeneralSettings/organizationSettingsForm.tsx
@@ -51,7 +51,7 @@ class OrganizationSettingsForm extends AsyncComponent<Props, State> {
{
name: 'codecovAccess',
type: 'boolean',
- label: t('Enable Codecov Access'),
+ label: t('Enable Code Coverage Insights - powered by Codecov'),
help: t('Opt-in to connect your codecov account'),
},
];
|
518e596c8b21fe0be34b59516a1826325ecbe2e0
|
2024-10-18 00:10:48
|
Michael Sun
|
fix(issue-views): Center justify the feedback button (#79289)
| false
|
Center justify the feedback button (#79289)
|
fix
|
diff --git a/static/app/views/issueList/groupSearchViewTabs/draggableTabMenuButton.tsx b/static/app/views/issueList/groupSearchViewTabs/draggableTabMenuButton.tsx
index 41abc060ae1c89..aad5709094e3ce 100644
--- a/static/app/views/issueList/groupSearchViewTabs/draggableTabMenuButton.tsx
+++ b/static/app/views/issueList/groupSearchViewTabs/draggableTabMenuButton.tsx
@@ -81,7 +81,7 @@ const SectionedOverlayFooter = styled('div')`
grid-area: footer;
display: flex;
align-items: center;
- justify-content: flex-end;
+ justify-content: center;
padding: ${space(1)};
border-top: 1px solid ${p => p.theme.innerBorder};
`;
|
080598378aeb41cf2d05d04acc6e92fde8bdc59a
|
2023-03-03 01:27:19
|
Vu Luong
|
feat(segmentedControl): Add optional `icon` prop (#45327)
| false
|
Add optional `icon` prop (#45327)
|
feat
|
diff --git a/static/app/components/segmentedControl.tsx b/static/app/components/segmentedControl.tsx
index ec31e0fa76ab55..88dce194bc7af1 100644
--- a/static/app/components/segmentedControl.tsx
+++ b/static/app/components/segmentedControl.tsx
@@ -11,12 +11,23 @@ import {LayoutGroup, motion} from 'framer-motion';
import InteractionStateLayer from 'sentry/components/interactionStateLayer';
import {InternalTooltipProps, Tooltip} from 'sentry/components/tooltip';
+import space from 'sentry/styles/space';
import {defined} from 'sentry/utils';
import {FormSize} from 'sentry/utils/theme';
-export interface SegmentedControlItemProps<Value extends string> extends ItemProps<any> {
+export interface SegmentedControlItemProps<Value extends string>
+ extends Omit<ItemProps<any>, 'children'> {
key: Value;
+ children?: React.ReactNode;
disabled?: boolean;
+ /**
+ * Optional icon to be rendered to the left of the segment label. Use this prop to
+ * ensure proper vertical alignment.
+ *
+ * NOTE: if the segment contains only an icon and no text label (i.e. `children` is
+ * not defined), then an `aria-label` must be provided for screen reader support.
+ */
+ icon?: React.ReactNode;
/**
* Optional tooltip that appears when the use hovers over the segment. Avoid using
* tooltips if there are other, more visible ways to display the same information.
@@ -99,7 +110,7 @@ SegmentedControl.Item = Item as <Value extends string>(
) => JSX.Element;
interface SegmentProps<Value extends string>
- extends Omit<SegmentedControlItemProps<Value>, keyof ItemProps<any>>,
+ extends SegmentedControlItemProps<Value>,
AriaRadioProps {
lastKey: string;
layoutGroupId: string;
@@ -119,6 +130,7 @@ function Segment<Value extends string>({
layoutGroupId,
tooltip,
tooltipOptions = {},
+ icon,
...props
}: SegmentProps<Value>) {
const ref = useRef<HTMLInputElement>(null);
@@ -157,15 +169,25 @@ function Segment<Value extends string>({
<Divider visible={showDivider} role="separator" aria-hidden />
- {/* Once an item is selected, it gets a heavier font weight and becomes slightly
- wider. To prevent layout shifts, we need a hidden container (HiddenLabel) that will
- always have normal weight to take up constant space; and a visible, absolutely
- positioned container (VisibleLabel) that doesn't affect the layout. */}
- <LabelWrap>
- <HiddenLabel aria-hidden>{props.children}</HiddenLabel>
- <VisibleLabel isSelected={isSelected} isDisabled={isDisabled} priority={priority}>
- {props.children}
- </VisibleLabel>
+ <LabelWrap size={size} role="presentation">
+ {icon}
+ {/* Once an item is selected, it gets a heavier font weight and becomes slightly
+ wider. To prevent layout shifts, we need a hidden container (HiddenLabel) that
+ will always have normal weight to take up constant space; and a visible,
+ absolutely positioned container (VisibleLabel) that doesn't affect the layout. */}
+ {props.children && (
+ <InnerLabelWrap role="presentation">
+ <HiddenLabel aria-hidden>{props.children}</HiddenLabel>
+ <VisibleLabel
+ isSelected={isSelected}
+ isDisabled={isDisabled}
+ priority={priority}
+ role="presentation"
+ >
+ {props.children}
+ </VisibleLabel>
+ </InnerLabelWrap>
+ )}
</LabelWrap>
</SegmentWrap>
);
@@ -205,9 +227,11 @@ const SegmentWrap = styled('label')<{
}>`
position: relative;
display: flex;
+ align-items: center;
margin: 0;
border-radius: calc(${p => p.theme.borderRadius} - 1px);
cursor: ${p => (p.isDisabled ? 'default' : 'pointer')};
+ min-height: 0;
min-width: 0;
${p => p.theme.buttonPadding[p.size]}
@@ -306,7 +330,15 @@ const SegmentSelectionIndicator = styled(motion.div)<{priority: Priority}>`
`}
`;
-const LabelWrap = styled('span')`
+const LabelWrap = styled('span')<{size: FormSize}>`
+ display: grid;
+ grid-auto-flow: column;
+ align-items: center;
+ gap: ${p => (p.size === 'xs' ? space(0.5) : space(0.75))};
+ z-index: 1;
+`;
+
+const InnerLabelWrap = styled('span')`
position: relative;
display: flex;
line-height: 1;
@@ -314,11 +346,10 @@ const LabelWrap = styled('span')`
`;
const HiddenLabel = styled('span')`
- display: inline-block;
+ ${p => p.theme.overflowEllipsis}
margin: 0 2px;
visibility: hidden;
user-select: none;
- ${p => p.theme.overflowEllipsis}
`;
function getTextColor({
@@ -350,10 +381,11 @@ const VisibleLabel = styled('span')<{
priority: Priority;
isDisabled?: boolean;
}>`
+ ${p => p.theme.overflowEllipsis}
+
position: absolute;
top: 50%;
left: 50%;
- width: max-content;
transform: translate(-50%, -50%);
transition: color 0.25s ease-out;
@@ -363,7 +395,6 @@ const VisibleLabel = styled('span')<{
text-align: center;
line-height: ${p => p.theme.text.lineHeightBody};
${getTextColor}
- ${p => p.theme.overflowEllipsis}
`;
const Divider = styled('div')<{visible: boolean}>`
|
2981c5968e9894d7778a8f7d1e3608743a447341
|
2023-05-23 23:56:14
|
Scott Cooper
|
fix(escalating): Change for review tab tooltip copy (#49626)
| false
|
Change for review tab tooltip copy (#49626)
|
fix
|
diff --git a/static/app/views/issueList/utils.tsx b/static/app/views/issueList/utils.tsx
index 4eb1c9835dd7e8..584de723f6e867 100644
--- a/static/app/views/issueList/utils.tsx
+++ b/static/app/views/issueList/utils.tsx
@@ -60,8 +60,11 @@ export function getTabs(organization: Organization) {
analyticsName: 'needs_review',
count: true,
enabled: true,
- tooltipTitle:
- t(`Issues are marked for review when they are created, unresolved, or unignored.
+ tooltipTitle: hasEscalatingIssuesUi
+ ? t(
+ 'Issues are marked for review if they are new or escalating, and have not been resolved or archived. Issues are automatically marked reviewed in 7 days.'
+ )
+ : t(`Issues are marked for review when they are created, unresolved, or unignored.
Mark an issue reviewed to move it out of this list.
Issues are automatically marked reviewed in 7 days.`),
},
|
b0b8d50bd3bfd0fbde08197e32062e1a7cf8392a
|
2018-03-08 00:36:20
|
Jess MacQueen
|
fix(ui): Add z-index to dropdown autocomplete
| false
|
Add z-index to dropdown autocomplete
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/dropdownAutoComplete.jsx b/src/sentry/static/sentry/app/components/dropdownAutoComplete.jsx
index b5c58e5da49a84..b6b605eeabeaae 100644
--- a/src/sentry/static/sentry/app/components/dropdownAutoComplete.jsx
+++ b/src/sentry/static/sentry/app/components/dropdownAutoComplete.jsx
@@ -198,6 +198,7 @@ const StyledMenu = styled('div')`
left: 0;
min-width: 250px;
font-size: 0.9em;
+ z-index: 1;
`;
export default DropdownAutoComplete;
|
265ced9a26a166397f9c3d68ba76339783c94a6b
|
2023-12-01 23:35:50
|
Tony Xiao
|
ref(stats-detectors): Unify breakpoint detection (#60973)
| false
|
Unify breakpoint detection (#60973)
|
ref
|
diff --git a/src/sentry/statistical_detectors/detector.py b/src/sentry/statistical_detectors/detector.py
index e9d2d20e83cec8..80aaec6a9cc5fc 100644
--- a/src/sentry/statistical_detectors/detector.py
+++ b/src/sentry/statistical_detectors/detector.py
@@ -9,9 +9,13 @@
import sentry_sdk
from sentry import options
+from sentry.api.serializers.snuba import SnubaTSResultSerializer
from sentry.models.project import Project
+from sentry.search.events.fields import get_function_alias
+from sentry.seer.utils import BreakpointData, detect_breakpoints
from sentry.utils import metrics
from sentry.utils.iterators import chunked
+from sentry.utils.snuba import SnubaTSResult
class TrendType(Enum):
@@ -95,6 +99,7 @@ class RegressionDetector(ABC):
store: DetectorStore
state_cls: type[DetectorState]
detector_cls: type[DetectorAlgorithm]
+ min_change: int
@classmethod
def all_payloads(
@@ -110,7 +115,6 @@ def all_payloads(
yield from cls.query_payloads(projects, start)
except Exception as e:
sentry_sdk.capture_exception(e)
- continue
@classmethod
@abstractmethod
@@ -194,3 +198,70 @@ def detect_trends(
tags={"source": cls.source, "kind": cls.kind},
sample_rate=1.0,
)
+
+ @classmethod
+ def all_timeseries(
+ cls, objects: List[Tuple[Project, int | str]], start: datetime, function: str, chunk_size=25
+ ) -> Generator[Tuple[int, int | str, SnubaTSResult], None, None]:
+ # Snuba allows 10,000 data points per request. 14 days * 1hr * 24hr =
+ # 336 data points per transaction name, so we can safely get 25 transaction
+ # timeseries.
+ for chunk in chunked(objects, chunk_size):
+ try:
+ yield from cls.query_timeseries(chunk, start, function)
+ except Exception as e:
+ sentry_sdk.capture_exception(e)
+
+ @classmethod
+ @abstractmethod
+ def query_timeseries(
+ cls,
+ objects: List[Tuple[Project, int | str]],
+ start: datetime,
+ function: str,
+ ) -> Iterable[Tuple[int, int | str, SnubaTSResult]]:
+ ...
+
+ @classmethod
+ def detect_regressions(
+ cls,
+ objects: List[Tuple[Project, int | str]],
+ start: datetime,
+ function: str,
+ timeseries_per_batch=10,
+ ) -> Generator[BreakpointData, None, None]:
+ serializer = SnubaTSResultSerializer(None, None, None)
+
+ for chunk in chunked(cls.all_timeseries(objects, start, function), timeseries_per_batch):
+ data = {}
+ for project_id, transaction_name, result in chunk:
+ serialized = serializer.serialize(result, get_function_alias(function))
+ data[f"{project_id},{transaction_name}"] = {
+ "data": serialized["data"],
+ "data_start": serialized["start"],
+ "data_end": serialized["end"],
+ # only look at the last 3 days of the request data
+ "request_start": serialized["end"] - 3 * 24 * 60 * 60,
+ "request_end": serialized["end"],
+ }
+
+ request = {
+ "data": data,
+ "sort": "-trend_percentage()",
+ "min_change()": cls.min_change,
+ # "trend_percentage()": 0.5, # require a minimum 50% increase
+ # "validate_tail_hours": 6,
+ # Disable the fall back to use the midpoint as the breakpoint
+ # which was originally intended to detect a gradual regression
+ # for the trends use case. That does not apply here.
+ "allow_midpoint": "0",
+ }
+
+ try:
+ yield from detect_breakpoints(request)["data"]
+ except Exception as e:
+ sentry_sdk.capture_exception(e)
+ metrics.incr(
+ "statistical_detectors.breakpoint.errors",
+ tags={"source": cls.source, "kind": cls.kind},
+ )
diff --git a/src/sentry/tasks/statistical_detectors.py b/src/sentry/tasks/statistical_detectors.py
index af916b1cd8aee3..6a5d8167674451 100644
--- a/src/sentry/tasks/statistical_detectors.py
+++ b/src/sentry/tasks/statistical_detectors.py
@@ -4,7 +4,7 @@
import logging
from collections import defaultdict
from datetime import datetime, timedelta
-from typing import Any, DefaultDict, Dict, Generator, List, Optional, Tuple, Union
+from typing import Any, DefaultDict, Dict, Generator, Iterable, List, Optional, Tuple
import sentry_sdk
from django.utils import timezone as django_timezone
@@ -179,15 +179,25 @@ class EndpointRegressionDetector(RegressionDetector):
store = RedisDetectorStore(detector_type=DetectorType.ENDPOINT) # e for endpoint
state_cls = MovingAverageDetectorState
detector_cls = MovingAverageRelativeChangeDetector
+ min_change = 200 # 200ms in ms
@classmethod
def query_payloads(
cls,
projects: List[Project],
start: datetime,
- ) -> List[DetectorPayload]:
+ ) -> Iterable[DetectorPayload]:
return query_transactions(projects, start)
+ @classmethod
+ def query_timeseries(
+ cls,
+ objects: List[Tuple[Project, int | str]],
+ start: datetime,
+ function: str,
+ ) -> Iterable[Tuple[int, int | str, SnubaTSResult]]:
+ return query_transactions_timeseries(objects, start, function)
+
class FunctionRegressionDetector(RegressionDetector):
source = "profile"
@@ -201,6 +211,7 @@ class FunctionRegressionDetector(RegressionDetector):
store = RedisDetectorStore(detector_type=DetectorType.FUNCTION)
state_cls = MovingAverageDetectorState
detector_cls = MovingAverageRelativeChangeDetector
+ min_change = 100_000_000 # 100ms in ns
@classmethod
def query_payloads(
@@ -210,6 +221,15 @@ def query_payloads(
) -> List[DetectorPayload]:
return query_functions(projects, start)
+ @classmethod
+ def query_timeseries(
+ cls,
+ objects: List[Tuple[Project, int | str]],
+ start: datetime,
+ function: str,
+ ) -> Iterable[Tuple[int, int | str, SnubaTSResult]]:
+ return query_functions_timeseries(objects, start, function)
+
@instrumented_task(
name="sentry.tasks.statistical_detectors.detect_transaction_trends",
@@ -267,13 +287,17 @@ def detect_transaction_change_points(
)
}
- transaction_pairs: List[Tuple[Project, Union[int, str]]] = [
+ transaction_pairs: List[Tuple[Project, int | str]] = [
(projects_by_id[item[0]], item[1]) for item in transactions if item[0] in projects_by_id
]
breakpoint_count = 0
- for regression in _detect_transaction_change_points(transaction_pairs, start):
+ regressions = EndpointRegressionDetector.detect_regressions(
+ transaction_pairs, start, "p95(transaction.duration)", TIMESERIES_PER_BATCH
+ )
+
+ for regression in regressions:
breakpoint_count += 1
send_regression_to_platform(regression, True)
@@ -285,214 +309,161 @@ def detect_transaction_change_points(
)
-def _detect_transaction_change_points(
- transactions: List[Tuple[Project, Union[int, str]]],
- start: datetime,
-) -> Generator[BreakpointData, None, None]:
- serializer = SnubaTSResultSerializer(None, None, None)
-
- trend_function = "p95(transaction.duration)"
-
- for chunk in chunked(
- query_transactions_timeseries(transactions, start, trend_function), TIMESERIES_PER_BATCH
- ):
- data = {}
- for project_id, transaction_name, result in chunk:
- serialized = serializer.serialize(result, get_function_alias(trend_function))
- data[f"{project_id},{transaction_name}"] = {
- "data": serialized["data"],
- "data_start": serialized["start"],
- "data_end": serialized["end"],
- # only look at the last 3 days of the request data
- "request_start": serialized["end"] - 3 * 24 * 60 * 60,
- "request_end": serialized["end"],
- }
-
- request = {
- "data": data,
- "sort": "-trend_percentage()",
- "min_change()": 200, # require a minimum 200ms increase (in ms)
- # "trend_percentage()": 0.5, # require a minimum 50% increase
- # "validate_tail_hours": 6,
- # Disable the fall back to use the midpoint as the breakpoint
- # which was originally intended to detect a gradual regression
- # for the trends use case. That does not apply here.
- "allow_midpoint": "0",
- }
-
- try:
- yield from detect_breakpoints(request)["data"]
- except Exception as e:
- sentry_sdk.capture_exception(e)
- metrics.incr(
- "statistical_detectors.breakpoint.errors",
- tags={"source": "transaction", "kind": "endpoint"},
- )
- continue
-
-
def query_transactions_timeseries(
transactions: List[Tuple[Project, int | str]],
start: datetime,
agg_function: str,
-) -> Generator[Tuple[int, Union[int, str], SnubaTSResult], None, None]:
+) -> Generator[Tuple[int, int | str, SnubaTSResult], None, None]:
end = start.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
days_to_query = options.get("statistical_detectors.query.transactions.timeseries_days")
start = end - timedelta(days=days_to_query)
use_case_id = UseCaseID.TRANSACTIONS
interval = 3600 # 1 hour
- # Snuba allows 10,000 data points per request. 14 days * 1hr * 24hr =
- # 336 data points per transaction name, so we can safely get 25 transaction
- # timeseries.
- chunk_size = 25
- for transaction_chunk in chunked(
- sorted(transactions, key=lambda transaction: (transaction[0].id, transaction[1])),
- chunk_size,
- ):
- project_objects = {p for p, _ in transaction_chunk}
- project_ids = [project.id for project in project_objects]
- org_ids = list({project.organization_id for project in project_objects})
- # The only tag available on DURATION_LIGHT is `transaction`: as long as
- # we don't filter on any other tags, DURATION_LIGHT's lower cardinality
- # will be faster to query.
- duration_metric_id = indexer.resolve(
- use_case_id, org_ids[0], str(TransactionMRI.DURATION_LIGHT.value)
+
+ project_objects = {p for p, _ in transactions}
+ project_ids = [project.id for project in project_objects]
+ org_ids = list({project.organization_id for project in project_objects})
+ # The only tag available on DURATION_LIGHT is `transaction`: as long as
+ # we don't filter on any other tags, DURATION_LIGHT's lower cardinality
+ # will be faster to query.
+ duration_metric_id = indexer.resolve(
+ use_case_id, org_ids[0], str(TransactionMRI.DURATION_LIGHT.value)
+ )
+ transaction_name_metric_id = indexer.resolve(
+ use_case_id,
+ org_ids[0],
+ "transaction",
+ )
+
+ transactions_condition = None
+ if len(transactions) == 1:
+ project, transaction_name = transactions[0]
+ transactions_condition = BooleanCondition(
+ BooleanOp.AND,
+ [
+ Condition(Column("project_id"), Op.EQ, project.id),
+ Condition(Column("transaction"), Op.EQ, transaction_name),
+ ],
)
- transaction_name_metric_id = indexer.resolve(
- use_case_id,
- org_ids[0],
- "transaction",
+ else:
+ transactions_condition = BooleanCondition(
+ BooleanOp.OR,
+ [
+ BooleanCondition(
+ BooleanOp.AND,
+ [
+ Condition(Column("project_id"), Op.EQ, project.id),
+ Condition(Column("transaction"), Op.EQ, transaction_name),
+ ],
+ )
+ for project, transaction_name in transactions
+ ],
)
- transactions_condition = None
- if len(transactions) == 1:
- project, transaction_name = transactions[0]
- transactions_condition = BooleanCondition(
- BooleanOp.AND,
- [
- Condition(Column("project_id"), Op.EQ, project.id),
- Condition(Column("transaction"), Op.EQ, transaction_name),
- ],
- )
- else:
- transactions_condition = BooleanCondition(
- BooleanOp.OR,
- [
- BooleanCondition(
- BooleanOp.AND,
- [
- Condition(Column("project_id"), Op.EQ, project.id),
- Condition(Column("transaction"), Op.EQ, transaction_name),
- ],
- )
- for project, transaction_name in transactions
- ],
- )
-
- query = Query(
- match=Entity(EntityKey.GenericMetricsDistributions.value),
- select=[
- Column("project_id"),
- Function(
- "arrayElement",
- (
- CurriedFunction(
- "quantilesIf",
- [0.95],
- (
- Column("value"),
- Function("equals", (Column("metric_id"), duration_metric_id)),
- ),
+ query = Query(
+ match=Entity(EntityKey.GenericMetricsDistributions.value),
+ select=[
+ Column("project_id"),
+ Function(
+ "arrayElement",
+ (
+ CurriedFunction(
+ "quantilesIf",
+ [0.95],
+ (
+ Column("value"),
+ Function("equals", (Column("metric_id"), duration_metric_id)),
),
- 1,
),
- "p95_transaction_duration",
+ 1,
),
- Function(
- "transform",
- (
- Column(f"tags_raw[{transaction_name_metric_id}]"),
- Function("array", ("",)),
- Function("array", ("<< unparameterized >>",)),
- ),
- "transaction",
+ "p95_transaction_duration",
+ ),
+ Function(
+ "transform",
+ (
+ Column(f"tags_raw[{transaction_name_metric_id}]"),
+ Function("array", ("",)),
+ Function("array", ("<< unparameterized >>",)),
),
- ],
- groupby=[
- Column("transaction"),
- Column("project_id"),
+ "transaction",
+ ),
+ ],
+ groupby=[
+ Column("transaction"),
+ Column("project_id"),
+ Function(
+ "toStartOfInterval",
+ (Column("timestamp"), Function("toIntervalSecond", (3600,)), "Universal"),
+ "time",
+ ),
+ ],
+ where=[
+ Condition(Column("org_id"), Op.IN, list(org_ids)),
+ Condition(Column("project_id"), Op.IN, list(project_ids)),
+ Condition(Column("timestamp"), Op.GTE, start),
+ Condition(Column("timestamp"), Op.LT, end),
+ Condition(Column("metric_id"), Op.EQ, duration_metric_id),
+ transactions_condition,
+ ],
+ orderby=[
+ OrderBy(Column("project_id"), Direction.ASC),
+ OrderBy(Column("transaction"), Direction.ASC),
+ OrderBy(
Function(
"toStartOfInterval",
(Column("timestamp"), Function("toIntervalSecond", (3600,)), "Universal"),
"time",
),
- ],
- where=[
- Condition(Column("org_id"), Op.IN, list(org_ids)),
- Condition(Column("project_id"), Op.IN, list(project_ids)),
- Condition(Column("timestamp"), Op.GTE, start),
- Condition(Column("timestamp"), Op.LT, end),
- Condition(Column("metric_id"), Op.EQ, duration_metric_id),
- transactions_condition,
- ],
- orderby=[
- OrderBy(Column("project_id"), Direction.ASC),
- OrderBy(Column("transaction"), Direction.ASC),
- OrderBy(
- Function(
- "toStartOfInterval",
- (Column("timestamp"), Function("toIntervalSecond", (3600,)), "Universal"),
- "time",
- ),
- Direction.ASC,
+ Direction.ASC,
+ ),
+ ],
+ granularity=Granularity(interval),
+ limit=Limit(10000),
+ )
+ request = Request(
+ dataset=Dataset.PerformanceMetrics.value,
+ app_id="statistical_detectors",
+ query=query,
+ tenant_ids={
+ "referrer": Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value,
+ "cross_org_query": 1,
+ "use_case_id": use_case_id.value,
+ },
+ )
+ data = raw_snql_query(
+ request, referrer=Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value
+ )["data"]
+
+ results = {}
+ for index, datapoint in enumerate(data or []):
+ key = (datapoint["project_id"], datapoint["transaction"])
+ if key not in results:
+ results[key] = {
+ "data": [datapoint],
+ }
+ else:
+ data = results[key]["data"]
+ data.append(datapoint)
+
+ for key, item in results.items():
+ project_id, transaction_name = key
+ formatted_result = SnubaTSResult(
+ {
+ "data": zerofill(
+ item["data"],
+ start,
+ end,
+ interval,
+ "time",
),
- ],
- granularity=Granularity(interval),
- limit=Limit(10000),
- )
- request = Request(
- dataset=Dataset.PerformanceMetrics.value,
- app_id="statistical_detectors",
- query=query,
- tenant_ids={
- "referrer": Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value,
- "cross_org_query": 1,
- "use_case_id": use_case_id.value,
+ "project": project_id,
},
+ start,
+ end,
+ interval,
)
- data = raw_snql_query(
- request, referrer=Referrer.STATISTICAL_DETECTORS_FETCH_TRANSACTION_TIMESERIES.value
- )["data"]
-
- results = {}
- for index, datapoint in enumerate(data or []):
- key = (datapoint["project_id"], datapoint["transaction"])
- if key not in results:
- results[key] = {
- "data": [datapoint],
- }
- else:
- data = results[key]["data"]
- data.append(datapoint)
-
- for key, item in results.items():
- project_id, transaction_name = key
- formatted_result = SnubaTSResult(
- {
- "data": zerofill(
- item["data"],
- start,
- end,
- interval,
- "time",
- ),
- "project": project_id,
- },
- start,
- end,
- interval,
- )
- yield project_id, transaction_name, formatted_result
+ yield project_id, transaction_name, formatted_result
@instrumented_task(
@@ -548,16 +519,20 @@ def detect_function_change_points(
)
}
+ function_pairs: List[Tuple[Project, int | str]] = [
+ (projects_by_id[item[0]], item[1]) for item in functions_list if item[0] in projects_by_id
+ ]
+
breakpoint_count = 0
emitted_count = 0
- breakpoints = _detect_function_change_points(projects_by_id, functions_list, start)
-
- chunk_size = 100
+ regressions = FunctionRegressionDetector.detect_regressions(
+ function_pairs, start, "p95()", TIMESERIES_PER_BATCH
+ )
- for breakpoint_chunk in chunked(breakpoints, chunk_size):
- breakpoint_count += len(breakpoint_chunk)
- emitted_count += emit_function_regression_issue(projects_by_id, breakpoint_chunk, start)
+ for regression_chunk in chunked(regressions, 100):
+ breakpoint_count += len(regression_chunk)
+ emitted_count += emit_function_regression_issue(projects_by_id, regression_chunk, start)
metrics.incr(
"statistical_detectors.breakpoint.detected",
@@ -581,7 +556,7 @@ def _detect_function_change_points(
) -> Generator[BreakpointData, None, None]:
serializer = SnubaTSResultSerializer(None, None, None)
- functions_list: List[Tuple[Project, int]] = [
+ functions_list: List[Tuple[Project, int | str]] = [
(projects_by_id[item[0]], item[1]) for item in functions_pairs if item[0] in projects_by_id
]
@@ -708,10 +683,10 @@ def emit_function_regression_issue(
def all_function_timeseries(
- functions_list: List[Tuple[Project, int]],
+ functions_list: List[Tuple[Project, int | str]],
start: datetime,
trend_function: str,
-) -> Generator[Tuple[int, int, Any], None, None]:
+) -> Generator[Tuple[int, int | str, SnubaTSResult], None, None]:
# make sure that each chunk can fit in the 10,000 row limit imposed by snuba
for functions_chunk in chunked(functions_list, 25):
try:
@@ -907,10 +882,10 @@ def query_functions(projects: List[Project], start: datetime) -> List[DetectorPa
def query_functions_timeseries(
- functions_list: List[Tuple[Project, int]],
+ functions_list: List[Tuple[Project, int | str]],
start: datetime,
agg_function: str,
-) -> Generator[Tuple[int, int, Any], None, None]:
+) -> Generator[Tuple[int, int | str, SnubaTSResult], None, None]:
projects = [project for project, _ in functions_list]
project_ids = [project.id for project in projects]
diff --git a/tests/sentry/tasks/test_statistical_detectors.py b/tests/sentry/tasks/test_statistical_detectors.py
index 808709310f7df2..1f92b32d226124 100644
--- a/tests/sentry/tasks/test_statistical_detectors.py
+++ b/tests/sentry/tasks/test_statistical_detectors.py
@@ -543,7 +543,7 @@ def test_detect_function_trends_ratelimit(
@mock.patch("sentry.tasks.statistical_detectors.emit_function_regression_issue")
[email protected]("sentry.tasks.statistical_detectors.detect_breakpoints")
[email protected]("sentry.statistical_detectors.detector.detect_breakpoints")
@mock.patch("sentry.tasks.statistical_detectors.raw_snql_query")
@django_db_all
def test_detect_function_change_points(
@@ -954,7 +954,7 @@ def test_query_transactions_single_timeseries(self) -> None:
assert len(results) == 1
@mock.patch("sentry.tasks.statistical_detectors.send_regression_to_platform")
- @mock.patch("sentry.tasks.statistical_detectors.detect_breakpoints")
+ @mock.patch("sentry.statistical_detectors.detector.detect_breakpoints")
def test_transaction_change_point_detection(
self, mock_detect_breakpoints, mock_send_regression_to_platform
) -> None:
|
9495b87b8850f102e14d9735cb5b11b1cc5596dc
|
2022-03-17 01:42:27
|
Evan Purkhiser
|
chore(deps): Upgrade webpack-remove-empty-scripts 0.7.1 -> 0.7.3 (#32681)
| false
|
Upgrade webpack-remove-empty-scripts 0.7.1 -> 0.7.3 (#32681)
|
chore
|
diff --git a/package.json b/package.json
index 40b95a4dbcfd59..3a1b1360aef49a 100644
--- a/package.json
+++ b/package.json
@@ -138,7 +138,7 @@
"u2f-api": "1.0.10",
"webpack": "5.66.0",
"webpack-cli": "4.9.2",
- "webpack-remove-empty-scripts": "^0.7.1",
+ "webpack-remove-empty-scripts": "^0.7.3",
"wink-jaro-distance": "^2.0.0",
"zxcvbn": "^4.4.2"
},
diff --git a/yarn.lock b/yarn.lock
index 98b6378a8d3455..04c0983677e575 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -5169,6 +5169,11 @@ ansicolor@^1.1.95:
resolved "https://registry.yarnpkg.com/ansicolor/-/ansicolor-1.1.95.tgz#978c494f04793d6c58115ba13a50f56593f736c6"
integrity sha512-R4yTmrfQZ2H9Wr5TZoM2iOz0+T6TNHqztpld7ZToaN8EaUj/06NG4r5UHQfegA9/+K/OY3E+WumprcglbcTMRA==
+ansis@^1.3.4:
+ version "1.3.4"
+ resolved "https://registry.yarnpkg.com/ansis/-/ansis-1.3.4.tgz#e94e32c6083c2eac9613ec6174c695a5bec9d9cb"
+ integrity sha512-BDXljGSG4gZXmWK64bQzXkI509i5fe8aAa9+eL29e3swaWUqxvxk/XlONjw9AUrNCpQWNdy++0GX7HAhWeR9BQ==
+
anymatch@^2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-2.0.0.tgz#bcb24b4f37934d9aa7ac17b4adaf89e7c76ef2eb"
@@ -15908,10 +15913,12 @@ webpack-merge@^5.7.3:
clone-deep "^4.0.1"
wildcard "^2.0.0"
-webpack-remove-empty-scripts@^0.7.1:
- version "0.7.1"
- resolved "https://registry.yarnpkg.com/webpack-remove-empty-scripts/-/webpack-remove-empty-scripts-0.7.1.tgz#486aeb618ee778e8951d1c086a8318be92230b98"
- integrity sha512-9GWBe8TxKUYMalR84L99QjME6W0ptd/pupNqB4Ad4NazouwT+9QJLcfJjl7PDhR/L+qY9JHlzIGdgj0Vv1f3zA==
+webpack-remove-empty-scripts@^0.7.3:
+ version "0.7.3"
+ resolved "https://registry.yarnpkg.com/webpack-remove-empty-scripts/-/webpack-remove-empty-scripts-0.7.3.tgz#f57b9823f5bd7016b44a4990f9257defd018513d"
+ integrity sha512-yipqb25A0qtH7X9vKt6yihwyYkTtSlRiDdBb2QsyrkqGM3hpfAcfOO1lYDef9HQUNm3s8ojmorbNg32XXX6FYg==
+ dependencies:
+ ansis "^1.3.4"
webpack-sources@^1.1.0:
version "1.4.3"
|
9e396dbb09c7fed25565ef7f479ed171c080831b
|
2021-09-17 23:37:33
|
Kev
|
fix(trends): Removed feature check that was breaking ops on trends (#28657)
| false
|
Removed feature check that was breaking ops on trends (#28657)
|
fix
|
diff --git a/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx b/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
index d84b9f70ef8fc0..5c3a207eee56b6 100644
--- a/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
+++ b/static/app/views/performance/transactionSummary/transactionOverview/charts.tsx
@@ -23,8 +23,8 @@ import {YAxis} from 'app/views/releases/detail/overview/chart/releaseChartContro
import {TrendColumnField, TrendFunctionField} from '../../trends/types';
import {
generateTrendFunctionAsString,
- getTrendsParameters,
TRENDS_FUNCTIONS,
+ TRENDS_PARAMETERS,
} from '../../trends/utils';
import {SpanOperationBreakdownFilter} from '../filter';
@@ -120,12 +120,12 @@ class TransactionSummaryCharts extends Component<Props> {
withoutZerofill,
} = this.props;
- const TREND_PARAMETERS_OPTIONS: SelectValue<string>[] = getTrendsParameters({
- canSeeSpanOpTrends: organization.features.includes('performance-ops-breakdown'),
- }).map(({column, label}) => ({
- value: column,
- label,
- }));
+ const TREND_PARAMETERS_OPTIONS: SelectValue<string>[] = TRENDS_PARAMETERS.map(
+ ({column, label}) => ({
+ value: column,
+ label,
+ })
+ );
let display = decodeScalar(location.query.display, DisplayModes.DURATION);
let trendFunction = decodeScalar(
diff --git a/static/app/views/performance/trends/content.tsx b/static/app/views/performance/trends/content.tsx
index c8fd13b67857e1..f33261778db1f0 100644
--- a/static/app/views/performance/trends/content.tsx
+++ b/static/app/views/performance/trends/content.tsx
@@ -31,10 +31,10 @@ import {
getCurrentTrendFunction,
getCurrentTrendParameter,
getSelectedQueryKey,
- getTrendsParameters,
modifyTrendsViewDefaultPeriod,
resetCursors,
TRENDS_FUNCTIONS,
+ TRENDS_PARAMETERS,
} from './utils';
type Props = {
@@ -195,10 +195,6 @@ class TrendsContent extends React.Component<Props, State> {
const currentTrendParameter = getCurrentTrendParameter(location);
const query = getTransactionSearchQuery(location);
- const TRENDS_PARAMETERS = getTrendsParameters({
- canSeeSpanOpTrends: organization.features.includes('performance-ops-breakdown'),
- });
-
return (
<GlobalSelectionHeader
defaultSelection={{
diff --git a/static/app/views/performance/trends/utils.tsx b/static/app/views/performance/trends/utils.tsx
index 349c3d2d4e9c7e..c6d97caa23117d 100644
--- a/static/app/views/performance/trends/utils.tsx
+++ b/static/app/views/performance/trends/utils.tsx
@@ -64,7 +64,7 @@ export const TRENDS_FUNCTIONS: TrendFunction[] = [
},
];
-const TRENDS_PARAMETERS: TrendParameter[] = [
+export const TRENDS_PARAMETERS: TrendParameter[] = [
{
label: 'Duration',
column: TrendColumnField.DURATION,
@@ -85,10 +85,6 @@ const TRENDS_PARAMETERS: TrendParameter[] = [
label: 'CLS',
column: TrendColumnField.CLS,
},
-];
-
-// TODO(perf): Merge with above after ops breakdown feature is mainlined.
-const SPANS_TRENDS_PARAMETERS: TrendParameter[] = [
{
label: 'Spans (http)',
column: TrendColumnField.SPANS_HTTP,
@@ -107,12 +103,6 @@ const SPANS_TRENDS_PARAMETERS: TrendParameter[] = [
},
];
-export function getTrendsParameters({canSeeSpanOpTrends} = {canSeeSpanOpTrends: false}) {
- return canSeeSpanOpTrends
- ? [...TRENDS_PARAMETERS, ...SPANS_TRENDS_PARAMETERS]
- : [...TRENDS_PARAMETERS];
-}
-
export const trendToColor = {
[TrendChangeType.IMPROVED]: {
lighter: theme.green200,
diff --git a/tests/js/spec/views/performance/trends/index.spec.jsx b/tests/js/spec/views/performance/trends/index.spec.jsx
index 0a18a8bbbd6a49..871d853dcc0da1 100644
--- a/tests/js/spec/views/performance/trends/index.spec.jsx
+++ b/tests/js/spec/views/performance/trends/index.spec.jsx
@@ -7,8 +7,8 @@ import ProjectsStore from 'app/stores/projectsStore';
import TrendsIndex from 'app/views/performance/trends/';
import {
DEFAULT_MAX_DURATION,
- getTrendsParameters,
TRENDS_FUNCTIONS,
+ TRENDS_PARAMETERS,
} from 'app/views/performance/trends/utils';
const trendsViewQuery = {
@@ -393,7 +393,7 @@ describe('Performance > Trends', function () {
await tick();
wrapper.update();
- for (const parameter of getTrendsParameters()) {
+ for (const parameter of TRENDS_PARAMETERS) {
selectTrendParameter(wrapper, parameter.label);
await tick();
|
8d4b9ccb38443ebd9d209c7f40b38f1917a191be
|
2023-07-12 22:59:13
|
Colleen O'Rourke
|
ref(rule): Allow migration to be re-run (#52735)
| false
|
Allow migration to be re-run (#52735)
|
ref
|
diff --git a/src/sentry/migrations/0507_delete_pending_deletion_rules.py b/src/sentry/migrations/0507_delete_pending_deletion_rules.py
index 0a73977efd4359..427189b513162f 100644
--- a/src/sentry/migrations/0507_delete_pending_deletion_rules.py
+++ b/src/sentry/migrations/0507_delete_pending_deletion_rules.py
@@ -27,9 +27,11 @@ def schedule(cls, instance, days=30):
app_label=instance._meta.app_label,
model_name=model_name,
object_id=instance.pk,
- date_scheduled=timezone.now() + timedelta(days=days, hours=0),
- data={},
- actor_id=None,
+ defaults={
+ "actor_id": None,
+ "data": {},
+ "date_scheduled": timezone.now() + timedelta(days=days, hours=0),
+ },
)
|
ee33a8fabdc295a7686753ad12ac52ae9133d1e6
|
2025-03-18 04:20:50
|
Brendan Hy
|
feat(profileHours): add ui profile hours to stats page (#87135)
| false
|
add ui profile hours to stats page (#87135)
|
feat
|
diff --git a/static/app/constants/index.tsx b/static/app/constants/index.tsx
index 4e3359d9fcbfd1..e5c7568b661ae5 100644
--- a/static/app/constants/index.tsx
+++ b/static/app/constants/index.tsx
@@ -377,6 +377,16 @@ export const DATA_CATEGORY_INFO = {
uid: 17,
isBilledCategory: false, // TODO(Continuous Profiling GA): make true for launch to show spend notification toggle
},
+ [DataCategoryExact.PROFILE_DURATION_UI]: {
+ name: DataCategoryExact.PROFILE_DURATION_UI,
+ apiName: 'profile_duration_ui',
+ plural: 'profileDurationUI',
+ displayName: 'UI profile hour',
+ titleName: t('UI Profile Hours'),
+ productName: t('UI Profiling'),
+ uid: 25,
+ isBilledCategory: false, // TODO(Continuous Profiling GA): make true for launch to show spend notification toggle
+ },
[DataCategoryExact.UPTIME]: {
name: DataCategoryExact.UPTIME,
apiName: 'uptime',
diff --git a/static/app/types/core.tsx b/static/app/types/core.tsx
index ffa5d90360b46c..867d8d6f8dc995 100644
--- a/static/app/types/core.tsx
+++ b/static/app/types/core.tsx
@@ -79,6 +79,7 @@ export enum DataCategory {
REPLAYS = 'replays',
MONITOR_SEATS = 'monitorSeats',
PROFILE_DURATION = 'profileDuration',
+ PROFILE_DURATION_UI = 'profileDurationUI',
SPANS = 'spans',
SPANS_INDEXED = 'spansIndexed',
PROFILE_CHUNKS = 'profileChunks',
@@ -102,6 +103,7 @@ export enum DataCategoryExact {
MONITOR = 'monitor',
MONITOR_SEAT = 'monitorSeat',
PROFILE_DURATION = 'profileDuration',
+ PROFILE_DURATION_UI = 'profileDurationUI',
SPAN = 'span',
SPAN_INDEXED = 'spanIndexed',
UPTIME = 'uptime',
diff --git a/static/app/utils/theme/theme.tsx b/static/app/utils/theme/theme.tsx
index d42f66cc802845..bec7a041ed3c60 100644
--- a/static/app/utils/theme/theme.tsx
+++ b/static/app/utils/theme/theme.tsx
@@ -911,7 +911,13 @@ const iconSizes: Sizes = {
const dataCategory: Record<
Exclude<
DataCategory,
- 'profiles' | 'profileChunks' | 'profileDuration' | 'spans' | 'spansIndexed' | 'uptime'
+ | 'profiles'
+ | 'profileChunks'
+ | 'profileDuration'
+ | 'profileDurationUI'
+ | 'spans'
+ | 'spansIndexed'
+ | 'uptime'
>,
string
> = {
diff --git a/static/app/views/organizationStats/index.tsx b/static/app/views/organizationStats/index.tsx
index 56d5d77a555e74..385b7d9e5155d4 100644
--- a/static/app/views/organizationStats/index.tsx
+++ b/static/app/views/organizationStats/index.tsx
@@ -263,7 +263,10 @@ export class OrganizationStats extends Component<OrganizationStatsProps> {
if (DATA_CATEGORY_INFO.transaction.plural === opt.value) {
return !organization.features.includes('spans-usage-tracking');
}
- if (DATA_CATEGORY_INFO.profileDuration.plural === opt.value) {
+ if (
+ DATA_CATEGORY_INFO.profileDuration.plural === opt.value ||
+ DATA_CATEGORY_INFO.profileDurationUI.plural === opt.value
+ ) {
return (
organization.features.includes('continuous-profiling-stats') ||
organization.features.includes('continuous-profiling')
diff --git a/static/app/views/organizationStats/usageChart/index.tsx b/static/app/views/organizationStats/usageChart/index.tsx
index 8ef12d12cad190..b56ae48ed9fff7 100644
--- a/static/app/views/organizationStats/usageChart/index.tsx
+++ b/static/app/views/organizationStats/usageChart/index.tsx
@@ -86,6 +86,12 @@ export const CHART_OPTIONS_DATACATEGORY: CategoryOption[] = [
disabled: false,
yAxisMinInterval: 100,
},
+ {
+ label: DATA_CATEGORY_INFO.profileDurationUI.titleName,
+ value: DATA_CATEGORY_INFO.profileDurationUI.plural,
+ disabled: false,
+ yAxisMinInterval: 100,
+ },
];
export enum ChartDataTransform {
|
58de2b21bcec1f67b0b6b22a0bd7394b97d7c61b
|
2025-03-19 03:58:50
|
Richard Roggenkemper
|
chore(issue-details): Improve event header on mobile (#87241)
| false
|
Improve event header on mobile (#87241)
|
chore
|
diff --git a/static/app/views/issueDetails/streamline/eventNavigation.tsx b/static/app/views/issueDetails/streamline/eventNavigation.tsx
index ba28e61afc0bd9..72b71b5b09c6b5 100644
--- a/static/app/views/issueDetails/streamline/eventNavigation.tsx
+++ b/static/app/views/issueDetails/streamline/eventNavigation.tsx
@@ -1,4 +1,5 @@
import {Fragment} from 'react';
+import {useTheme} from '@emotion/react';
import styled from '@emotion/styled';
import ButtonBar from 'sentry/components/buttonBar';
@@ -19,6 +20,7 @@ import parseLinkHeader from 'sentry/utils/parseLinkHeader';
import {keepPreviousData} from 'sentry/utils/queryClient';
import useReplayCountForIssues from 'sentry/utils/replayCount/useReplayCountForIssues';
import {useLocation} from 'sentry/utils/useLocation';
+import useMedia from 'sentry/utils/useMedia';
import useOrganization from 'sentry/utils/useOrganization';
import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
import {useGroupEventAttachments} from 'sentry/views/issueDetails/groupEventAttachments/useGroupEventAttachments';
@@ -51,6 +53,8 @@ export function IssueEventNavigation({event, group}: IssueEventNavigationProps)
const eventView = useIssueDetailsEventView({group});
const {eventCount} = useIssueDetails();
const issueTypeConfig = getConfigForIssueType(group, group.project);
+ const theme = useTheme();
+ const isSmallScreen = useMedia(`(max-width: ${theme.breakpoints.small})`);
const hideDropdownButton =
!issueTypeConfig.pages.attachments.enabled &&
@@ -213,7 +217,9 @@ export function IssueEventNavigation({event, group}: IssueEventNavigationProps)
analyticsEventKey="issue_details.all_events_clicked"
analyticsEventName="Issue Details: All Events Clicked"
>
- {t('View More %s', issueTypeConfig.customCopy.eventUnits)}
+ {isSmallScreen
+ ? t('More %s', issueTypeConfig.customCopy.eventUnits)
+ : t('View More %s', issueTypeConfig.customCopy.eventUnits)}
</LinkButton>
)}
{issueTypeConfig.pages.openPeriods.enabled && (
@@ -226,7 +232,7 @@ export function IssueEventNavigation({event, group}: IssueEventNavigationProps)
analyticsEventKey="issue_details.all_open_periods_clicked"
analyticsEventName="Issue Details: All Open Periods Clicked"
>
- {t('View More Open Periods')}
+ {isSmallScreen ? t('More Open Periods') : t('View More Open Periods')}
</LinkButton>
)}
{issueTypeConfig.pages.checkIns.enabled && (
@@ -239,7 +245,7 @@ export function IssueEventNavigation({event, group}: IssueEventNavigationProps)
analyticsEventKey="issue_details.all_checks_ins_clicked"
analyticsEventName="Issue Details: All Checks-Ins Clicked"
>
- {t('View More Check-Ins')}
+ {isSmallScreen ? t('More Check-Ins') : t('View More Check-Ins')}
</LinkButton>
)}
{issueTypeConfig.pages.uptimeChecks.enabled && (
@@ -252,7 +258,7 @@ export function IssueEventNavigation({event, group}: IssueEventNavigationProps)
analyticsEventKey="issue_details.all_uptime_checks_clicked"
analyticsEventName="Issue Details: All Uptime Checks Clicked"
>
- {t('View More Uptime Checks')}
+ {isSmallScreen ? t('More Uptime Checks') : t('View More Uptime Checks')}
</LinkButton>
)}
</Fragment>
diff --git a/static/app/views/issueDetails/streamline/eventTitle.tsx b/static/app/views/issueDetails/streamline/eventTitle.tsx
index 713231c0aaf4d4..c215dcf8bd8bcd 100644
--- a/static/app/views/issueDetails/streamline/eventTitle.tsx
+++ b/static/app/views/issueDetails/streamline/eventTitle.tsx
@@ -229,11 +229,12 @@ const EventInfoJumpToWrapper = styled('div')`
flex-direction: row;
justify-content: space-between;
align-items: center;
- padding: 0 ${space(2)} 0 ${space(0.5)};
- flex-wrap: wrap;
+ padding: 0 ${space(2)};
+ flex-wrap: nowrap;
min-height: ${MIN_NAV_HEIGHT}px;
- @media (min-width: ${p => p.theme.breakpoints.small}) {
- flex-wrap: nowrap;
+ @media (max-width: ${p => p.theme.breakpoints.small}) {
+ flex-wrap: wrap;
+ gap: 0;
}
border-bottom: 1px solid ${p => p.theme.translucentBorder};
`;
@@ -244,6 +245,10 @@ const EventInfo = styled('div')`
flex-direction: row;
align-items: center;
line-height: 1.2;
+
+ @media (max-width: ${p => p.theme.breakpoints.small}) {
+ padding-top: ${space(1)};
+ }
`;
const JumpTo = styled('div')`
@@ -290,7 +295,6 @@ const EventIdWrapper = styled('div')`
display: flex;
gap: ${space(0.25)};
align-items: center;
- margin-left: ${space(1.5)};
font-weight: ${p => p.theme.fontWeightBold};
button {
|
702d660cd5cbd318c90595204deadbc463b15076
|
2024-02-12 23:12:07
|
Kyle Mumma
|
ref(snuba): add typing to utils/snuba.py (SNS-2588) (#64310)
| false
|
add typing to utils/snuba.py (SNS-2588) (#64310)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index 07c0102a5d518e..dd9ebd701dbe12 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -529,7 +529,6 @@ module = [
"sentry.utils.sentry_apps.webhooks",
"sentry.utils.services",
"sentry.utils.snowflake",
- "sentry.utils.snuba",
"sentry.utils.suspect_resolutions.get_suspect_resolutions",
"sentry.utils.suspect_resolutions_releases.get_suspect_resolutions_releases",
"sentry.web.client_config",
diff --git a/src/sentry/utils/snuba.py b/src/sentry/utils/snuba.py
index ef0d34f72cbf88..8f2a0155b02b4e 100644
--- a/src/sentry/utils/snuba.py
+++ b/src/sentry/utils/snuba.py
@@ -6,7 +6,7 @@
import re
import time
from collections import namedtuple
-from collections.abc import Callable, Mapping, MutableMapping, Sequence
+from collections.abc import Callable, Collection, Mapping, MutableMapping, Sequence
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import deepcopy
@@ -428,7 +428,7 @@ def to_naive_timestamp(value):
return (value - epoch_naive).total_seconds()
-def to_start_of_hour(dt: datetime) -> datetime:
+def to_start_of_hour(dt: datetime) -> str:
"""This is a function that mimics toStartOfHour from Clickhouse"""
return dt.replace(minute=0, second=0, microsecond=0).isoformat()
@@ -522,7 +522,9 @@ def infer_project_ids_from_related_models(filter_keys: Mapping[str, Sequence[int
return list(set.union(*ids))
-def get_query_params_to_update_for_projects(query_params, with_org=False):
+def get_query_params_to_update_for_projects(
+ query_params: SnubaQueryParams, with_org: bool = False
+) -> tuple[int, dict[str, Any]]:
"""
Get the project ID and query params that need to be updated for project
based datasets, before we send the query to Snuba.
@@ -549,7 +551,7 @@ def get_query_params_to_update_for_projects(query_params, with_org=False):
organization_id = get_organization_id_from_project_ids(project_ids)
- params = {"project": project_ids}
+ params: dict[str, Any] = {"project": project_ids}
if with_org:
params["organization"] = organization_id
@@ -907,9 +909,11 @@ def _apply_cache_and_build_results(
if to_query:
query_results = _bulk_snuba_query([item[1] for item in to_query], headers)
- for result, (query_pos, _, cache_key) in zip(query_results, to_query):
- if cache_key:
- cache.set(cache_key, json.dumps(result), settings.SENTRY_SNUBA_CACHE_TTL_SECONDS)
+ for result, (query_pos, _, opt_cache_key) in zip(query_results, to_query):
+ if opt_cache_key:
+ cache.set(
+ opt_cache_key, json.dumps(result), settings.SENTRY_SNUBA_CACHE_TTL_SECONDS
+ )
results.append((query_pos, result))
# Sort so that we get the results back in the original param list order
@@ -979,19 +983,7 @@ def _bulk_snuba_query(
raise UnexpectedResponseError(f"Could not decode JSON response: {response.data!r}")
if response.status != 200:
- error_query = snuba_param_list[index][0]
- if isinstance(error_query, Request):
- query_str = error_query.serialize()
- query_type = "mql" if isinstance(error_query.query, MetricsQuery) else "snql"
- else:
- query_str = json.dumps(error_query)
- query_type = "snql"
- sentry_sdk.add_breadcrumb(
- category="query_info",
- level="info",
- message=f"{query_type}_query",
- data={query_type: query_str},
- )
+ _log_request_query(snuba_param_list[index][0])
if body.get("error"):
error = body["error"]
@@ -1015,6 +1007,18 @@ def _bulk_snuba_query(
return results
+def _log_request_query(req: Request) -> None:
+ """Given a request, logs its associated query in sentry breadcrumbs"""
+ query_str = req.serialize()
+ query_type = "mql" if isinstance(req.query, MetricsQuery) else "snql"
+ sentry_sdk.add_breadcrumb(
+ category="query_info",
+ level="info",
+ message=f"{query_type}_query",
+ data={query_type: query_str},
+ )
+
+
RawResult = tuple[urllib3.response.HTTPResponse, Callable[[Any], Any], Callable[[Any], Any]]
@@ -1147,7 +1151,11 @@ def query(
return nest_groups(body["data"], groupby, aggregate_names + selected_names)
-def nest_groups(data, groups, aggregate_cols):
+def nest_groups(
+ data: Sequence[MutableMapping],
+ groups: Sequence[str] | None,
+ aggregate_cols: Sequence[str],
+) -> dict | Any:
"""
Build a nested mapping from query response rows. Each group column
gives a new level of nesting and the leaf result is the aggregate
@@ -1161,14 +1169,14 @@ def nest_groups(data, groups, aggregate_cols):
return {c: data[0][c] for c in aggregate_cols} if data else None
else:
g, rest = groups[0], groups[1:]
- inter = {}
+ inter: dict[Any, Any] = {}
for d in data:
inter.setdefault(d[g], []).append(d)
return {k: nest_groups(v, rest, aggregate_cols) for k, v in inter.items()}
-def resolve_column(dataset) -> Callable[[str], str]:
- def _resolve_column(col: str) -> str:
+def resolve_column(dataset) -> Callable:
+ def _resolve_column(col):
if col is None:
return col
if isinstance(col, int) or isinstance(col, float):
@@ -1208,7 +1216,7 @@ def _resolve_column(col: str) -> str:
return _resolve_column
-def resolve_condition(cond, column_resolver):
+def resolve_condition(cond: list, column_resolver: Callable[[Any], Any]) -> list:
"""
When conditions have been parsed by the api.event_search module
we can end up with conditions that are not valid on the current dataset
@@ -1238,7 +1246,7 @@ def _passthrough_arg(arg):
func_args = cond[index + 1]
for i, arg in enumerate(func_args):
if i == 0:
- if isinstance(arg, (list, tuple)):
+ if isinstance(arg, list):
func_args[i] = resolve_condition(arg, column_resolver)
else:
func_args[i] = column_resolver(arg)
@@ -1252,7 +1260,7 @@ def _passthrough_arg(arg):
for i, arg in enumerate(func_args):
# Nested function
try:
- if isinstance(arg, (list, tuple)):
+ if isinstance(arg, list):
func_args[i] = resolve_condition(arg, column_resolver)
else:
func_args[i] = column_resolver(arg)
@@ -1267,7 +1275,7 @@ def _passthrough_arg(arg):
if isinstance(cond[0], str) and len(cond) == 3:
cond[0] = column_resolver(cond[0])
return cond
- if isinstance(cond[0], (list, tuple)):
+ if isinstance(cond[0], list):
if get_function_index(cond[0]) is not None:
cond[0] = resolve_condition(cond[0], column_resolver)
return cond
@@ -1298,8 +1306,8 @@ def _aliased_query_impl(**kwargs):
def resolve_conditions(
- conditions: Sequence[Any] | None, column_resolver: Callable[[str], str]
-) -> Sequence[Any] | None:
+ conditions: Sequence | None, column_resolver: Callable[[Any], Any]
+) -> list | None:
if conditions is None:
return conditions
@@ -1324,9 +1332,9 @@ def aliased_query_params(
having=None,
dataset=None,
orderby=None,
- condition_resolver=None,
+ condition_resolver: Callable | None = None,
**kwargs,
-) -> Mapping[str, Any]:
+) -> dict[str, Any]:
if dataset is None:
raise ValueError("A dataset is required, and is no longer automatically detected.")
@@ -1345,11 +1353,10 @@ def aliased_query_params(
derived_columns.append(aggregation[2])
if conditions:
- column_resolver = (
- functools.partial(condition_resolver, dataset=dataset)
- if condition_resolver
- else resolve_func
- )
+ if condition_resolver:
+ column_resolver: Callable = functools.partial(condition_resolver, dataset=dataset)
+ else:
+ column_resolver = resolve_func
resolved_conditions = resolve_conditions(conditions, column_resolver)
else:
resolved_conditions = conditions
@@ -1490,7 +1497,7 @@ def get_snuba_translators(filter_keys, is_grouprelease=False):
Release.objects.filter(id__in=[x[2] for x in gr_map]).values_list("id", "version")
)
fwd_map = {gr: (group, ver[release]) for (gr, group, release) in gr_map}
- rev_map = dict(reversed(t) for t in fwd_map.items())
+ rev_map = {v: k for k, v in fwd_map.items()}
fwd = (
lambda col, trans: lambda filters: replace(
filters, col, [trans[k][1] for k in filters[col]]
@@ -1510,7 +1517,7 @@ def get_snuba_translators(filter_keys, is_grouprelease=False):
fwd_map = {
k: fmt(v) for k, v in model.objects.filter(id__in=ids).values_list("id", field)
}
- rev_map = dict(reversed(t) for t in fwd_map.items())
+ rev_map = {v: k for k, v in fwd_map.items()}
fwd = (
lambda col, trans: lambda filters: replace(
filters, col, [trans[k] for k in filters[col] if k]
@@ -1569,7 +1576,7 @@ def get_related_project_ids(column, ids):
return []
-def shrink_time_window(issues, start):
+def shrink_time_window(issues: Collection | None, start: datetime) -> datetime:
"""\
If a single issue is passed in, shrink the `start` parameter to be briefly before
the `first_seen` in order to hopefully eliminate a large percentage of rows scanned.
@@ -1588,7 +1595,7 @@ def shrink_time_window(issues, start):
return start
-def naiveify_datetime(dt):
+def naiveify_datetime(dt: datetime) -> datetime:
return dt if not dt.tzinfo else dt.astimezone(timezone.utc).replace(tzinfo=None)
|
0de707a11bf43095d1025366987d12930aad6171
|
2020-02-28 03:36:16
|
josh
|
feat: bump ua-parser to 0.10.x (#17358)
| false
|
bump ua-parser to 0.10.x (#17358)
|
feat
|
diff --git a/requirements-base.txt b/requirements-base.txt
index a7089665e40e8b..6da53e65ee7f4a 100644
--- a/requirements-base.txt
+++ b/requirements-base.txt
@@ -58,7 +58,7 @@ statsd>=3.1.0,<3.2.0
structlog==16.1.0
symbolic>=7.1.0,<8.0.0
toronado>=0.0.11,<0.1.0
-ua-parser>=0.6.1,<0.8.0
+ua-parser>=0.10.0,<0.11.0
unidiff>=0.5.4
urllib3==1.24.2
uwsgi>2.0.0,<2.1.0
|
f476d5994b64164db62fdece89c89f2edd2e6eb4
|
2024-04-23 21:58:48
|
Josh Ferge
|
feat(feedback): dont send notifications for spam messages (#69478)
| false
|
dont send notifications for spam messages (#69478)
|
feat
|
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index 00bb66ed0ce2ab..a6c9c2063bf986 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -1432,6 +1432,9 @@ def should_postprocess_feedback(job: PostProcessJob) -> bool:
if not hasattr(event, "occurrence") or event.occurrence is None:
return False
+ if event.occurrence.evidence_data.get("is_spam") is True:
+ return False
+
feedback_source = event.occurrence.evidence_data.get("source")
if feedback_source in FeedbackCreationSource.new_feedback_category_values():
diff --git a/tests/sentry/tasks/test_post_process.py b/tests/sentry/tasks/test_post_process.py
index fee20892e1ef91..412b1d30bc63de 100644
--- a/tests/sentry/tasks/test_post_process.py
+++ b/tests/sentry/tasks/test_post_process.py
@@ -2708,12 +2708,24 @@ def create_event(
project_id,
assert_no_errors=True,
feedback_type=FeedbackCreationSource.NEW_FEEDBACK_ENVELOPE,
+ is_spam=False,
):
data["type"] = "generic"
event = self.store_event(
data=data, project_id=project_id, assert_no_errors=assert_no_errors
)
+ evidence_data = {
+ "Test": 123,
+ "source": feedback_type.value,
+ }
+ evidence_display = [
+ {"name": "hi", "value": "bye", "important": True},
+ {"name": "what", "value": "where", "important": False},
+ ]
+ if is_spam:
+ evidence_data["is_spam"] = True
+
occurrence_data = self.build_occurrence_data(
event_id=event.event_id,
project_id=project_id,
@@ -2724,14 +2736,8 @@ def create_event(
"subtitle": "it was bad",
"culprit": "api/123",
"resource_id": "1234",
- "evidence_data": {
- "Test": 123,
- "source": feedback_type.value,
- },
- "evidence_display": [
- {"name": "hi", "value": "bye", "important": True},
- {"name": "what", "value": "where", "important": False},
- ],
+ "evidence_data": evidence_data,
+ "evidence_display": evidence_display,
"type": FeedbackGroup.type_id,
"detection_time": datetime.now().timestamp(),
"level": "info",
@@ -2784,6 +2790,31 @@ def test_not_ran_if_crash_report_option_disabled(self):
)
assert mock_process_func.call_count == 0
+ def test_not_ran_if_spam(self):
+ event = self.create_event(
+ data={},
+ project_id=self.project.id,
+ feedback_type=FeedbackCreationSource.CRASH_REPORT_EMBED_FORM,
+ is_spam=True,
+ )
+ mock_process_func = Mock()
+ with patch(
+ "sentry.tasks.post_process.GROUP_CATEGORY_POST_PROCESS_PIPELINE",
+ {
+ GroupCategory.FEEDBACK: [
+ feedback_filter_decorator(mock_process_func),
+ ]
+ },
+ ):
+ self.call_post_process_group(
+ is_new=True,
+ is_regression=False,
+ is_new_group_environment=True,
+ event=event,
+ cache_key="total_rubbish",
+ )
+ assert mock_process_func.call_count == 0
+
def test_not_ran_if_crash_report_project_option_enabled(self):
self.project.update_option("sentry:feedback_user_report_notifications", True)
|
2cc5cc547644c8a567bf0478a151c8e2c2b4559e
|
2022-12-02 01:24:51
|
Armen Zambrano G
|
feat(derive-code-mappings): For dry run orgs, process Javascript events (#41933)
| false
|
For dry run orgs, process Javascript events (#41933)
|
feat
|
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index 12d2486e14bba1..f966f5b3b0aa26 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -610,8 +610,8 @@ def process_code_mappings(job: PostProcessJob) -> None:
event = job["event"]
project = event.project
- # We're currently only processing code mappings for python events
- if event.data["platform"] != "python":
+ # Supported platforms
+ if event.data["platform"] not in ["javascript", "python"]:
return
cache_key = f"code-mappings:{project.id}"
@@ -624,15 +624,22 @@ def process_code_mappings(job: PostProcessJob) -> None:
org_slug = project.organization.slug
next_time = timezone.now() + timedelta(hours=1)
- if features.has("organizations:derive-code-mappings", event.project.organization):
+ has_normal_run_flag = features.has(
+ "organizations:derive-code-mappings", event.project.organization
+ )
+ has_dry_run_flag = features.has(
+ "organizations:derive-code-mappings-dry-run", event.project.organization
+ )
+
+ # Right now EA orgs have both flags on, thus, only supporting dry run
+ if has_normal_run_flag and event.data["platform"] == "python":
logger.info(
f"derive_code_mappings: Queuing code mapping derivation for {project.slug=} {event.group_id=}."
+ f" Future events in {org_slug=} will not have not have code mapping derivation until {next_time}"
)
derive_code_mappings.delay(project.id, event.data, dry_run=False)
-
# Derive code mappings with dry_run=True to validate the generated mappings.
- elif features.has("organizations:derive-code-mappings-dry-run", event.project.organization):
+ elif has_dry_run_flag:
logger.info(
f"derive_code_mappings: Queuing dry run code mapping derivation for {project.slug=} {event.group_id=}."
+ f" Future events in {org_slug=} will not have not have code mapping derivation until {next_time}"
diff --git a/tests/sentry/tasks/test_post_process.py b/tests/sentry/tasks/test_post_process.py
index bcb94fb290261f..4db6c5eb041819 100644
--- a/tests/sentry/tasks/test_post_process.py
+++ b/tests/sentry/tasks/test_post_process.py
@@ -2,6 +2,7 @@
import abc
from datetime import timedelta
+from typing import Dict
from unittest import mock
from unittest.mock import Mock, patch
@@ -152,6 +153,41 @@ def test_processing_cache_cleared_with_commits(self):
assert event_processing_store.get(cache_key) is None
+@apply_feature_flag_on_cls("organizations:derive-code-mappings")
+@apply_feature_flag_on_cls("organizations:derive-code-mappings-dry-run")
+class DeriveCodeMappingsProcessGroupTestMixin(BasePostProgressGroupMixin):
+ def _call_post_process_group(self, data: Dict[str, str]) -> None:
+ event = self.store_event(data=data, project_id=self.project.id)
+ cache_key = write_event_to_cache(event)
+ self.call_post_process_group(
+ is_new=True,
+ is_regression=False,
+ is_new_group_environment=True,
+ cache_key=cache_key,
+ group_id=event.group_id,
+ )
+
+ @patch("sentry.tasks.derive_code_mappings.derive_code_mappings")
+ def test_derive_invalid_platform(self, mock_derive_code_mappings):
+ self._call_post_process_group({"platform": "elixir"})
+ assert mock_derive_code_mappings.delay.call_count == 0
+
+ @patch("sentry.tasks.derive_code_mappings.derive_code_mappings")
+ def test_derive_python(self, mock_derive_code_mappings):
+ data = {"platform": "python"}
+ self._call_post_process_group(data)
+ assert mock_derive_code_mappings.delay.call_count == 1
+ assert mock_derive_code_mappings.delay.called_with(self.project.id, data, False)
+
+ @patch("sentry.tasks.derive_code_mappings.derive_code_mappings")
+ def test_derive_js(self, mock_derive_code_mappings):
+ data = {"platform": "javascript"}
+ self._call_post_process_group(data)
+ assert mock_derive_code_mappings.delay.call_count == 1
+ # Because we only run on dry run mode even if the official flag is set
+ assert mock_derive_code_mappings.delay.called_with(self.project.id, data, True)
+
+
class RuleProcessorTestMixin(BasePostProgressGroupMixin):
@patch("sentry.rules.processor.RuleProcessor")
def test_rule_processor_backwards_compat(self, mock_processor):
@@ -1075,6 +1111,7 @@ class PostProcessGroupErrorTest(
TestCase,
AssignmentTestMixin,
CorePostProcessGroupTestMixin,
+ DeriveCodeMappingsProcessGroupTestMixin,
InboxTestMixin,
ResourceChangeBoundsTestMixin,
RuleProcessorTestMixin,
|
cb0732f60c20e8f70b641a7b319ed3015d3950ac
|
2018-06-01 20:22:46
|
Matt Robenolt
|
fix(tests): Don't assume local Postgres is accessible over Unix socket
| false
|
Don't assume local Postgres is accessible over Unix socket
|
fix
|
diff --git a/src/sentry/utils/pytest/sentry.py b/src/sentry/utils/pytest/sentry.py
index 90fad556b35499..8abdbb82d6565f 100644
--- a/src/sentry/utils/pytest/sentry.py
+++ b/src/sentry/utils/pytest/sentry.py
@@ -51,6 +51,7 @@ def pytest_configure(config):
'ENGINE': 'sentry.db.postgres',
'USER': 'postgres',
'NAME': 'sentry',
+ 'HOST': '127.0.0.1',
}
)
# postgres requires running full migration all the time
|
4b74a73ccf1a5313d1cca3ac00b6863ed596d402
|
2021-03-08 23:43:12
|
Tony
|
feat(trace-view): Add transaction and project count to trace view (#24266)
| false
|
Add transaction and project count to trace view (#24266)
|
feat
|
diff --git a/src/sentry/static/sentry/app/utils/performance/quickTrace/quickTraceQuery.tsx b/src/sentry/static/sentry/app/utils/performance/quickTrace/quickTraceQuery.tsx
index f28bec3ae9d41b..c232e71d26a7c4 100644
--- a/src/sentry/static/sentry/app/utils/performance/quickTrace/quickTraceQuery.tsx
+++ b/src/sentry/static/sentry/app/utils/performance/quickTrace/quickTraceQuery.tsx
@@ -1,23 +1,54 @@
import React from 'react';
import * as Sentry from '@sentry/react';
+import {getTraceDateTimeRange} from 'app/components/events/interfaces/spans/utils';
+import {Event} from 'app/types/event';
+import {DiscoverQueryProps} from 'app/utils/discover/genericDiscoverQuery';
import TraceFullQuery from 'app/utils/performance/quickTrace/traceFullQuery';
import TraceLiteQuery from 'app/utils/performance/quickTrace/traceLiteQuery';
+import {QuickTraceQueryChildrenProps} from 'app/utils/performance/quickTrace/types';
import {
- QuickTraceQueryChildrenProps,
- TraceRequestProps,
-} from 'app/utils/performance/quickTrace/types';
-import {flattenRelevantPaths} from 'app/utils/performance/quickTrace/utils';
+ flattenRelevantPaths,
+ isTransaction,
+} from 'app/utils/performance/quickTrace/utils';
-type QueryProps = Omit<TraceRequestProps, 'api' | 'eventView'> & {
+type QueryProps = Omit<DiscoverQueryProps, 'api' | 'eventView'> & {
+ event: Event;
children: (props: QuickTraceQueryChildrenProps) => React.ReactNode;
};
-export default function QuickTraceQuery({children, ...props}: QueryProps) {
+export default function QuickTraceQuery({children, event, ...props}: QueryProps) {
+ const traceId = event.contexts?.trace?.trace_id;
+
+ // non transaction events are currently unsupported
+ if (!isTransaction(event) || !traceId) {
+ return (
+ <React.Fragment>
+ {children({
+ isLoading: false,
+ error: null,
+ trace: [],
+ type: 'empty',
+ })}
+ </React.Fragment>
+ );
+ }
+
+ const {start, end} = getTraceDateTimeRange({
+ start: event.startTimestamp,
+ end: event.endTimestamp,
+ });
+
return (
- <TraceLiteQuery {...props}>
+ <TraceLiteQuery
+ eventId={event.id}
+ traceId={traceId}
+ start={start}
+ end={end}
+ {...props}
+ >
{traceLiteResults => (
- <TraceFullQuery {...props}>
+ <TraceFullQuery traceId={traceId} start={start} end={end} {...props}>
{traceFullResults => {
if (
!traceFullResults.isLoading &&
@@ -25,13 +56,13 @@ export default function QuickTraceQuery({children, ...props}: QueryProps) {
traceFullResults.trace !== null
) {
try {
- const trace = flattenRelevantPaths(props.event, traceFullResults.trace);
+ const trace = flattenRelevantPaths(event, traceFullResults.trace);
return children({
...traceFullResults,
trace,
});
} catch (error) {
- Sentry.setTag('current.trace_id', props.event.contexts?.trace?.trace_id);
+ Sentry.setTag('current.trace_id', traceId);
Sentry.captureException(error);
}
}
diff --git a/src/sentry/static/sentry/app/utils/performance/quickTrace/traceFullQuery.tsx b/src/sentry/static/sentry/app/utils/performance/quickTrace/traceFullQuery.tsx
index f7611bddc4572a..c887474e8f0530 100644
--- a/src/sentry/static/sentry/app/utils/performance/quickTrace/traceFullQuery.tsx
+++ b/src/sentry/static/sentry/app/utils/performance/quickTrace/traceFullQuery.tsx
@@ -4,18 +4,16 @@ import GenericDiscoverQuery from 'app/utils/discover/genericDiscoverQuery';
import {
TraceFull,
TraceFullQueryChildrenProps,
- TraceProps,
TraceRequestProps,
} from 'app/utils/performance/quickTrace/types';
import {
beforeFetch,
getQuickTraceRequestPayload,
- isTransaction,
makeEventView,
} from 'app/utils/performance/quickTrace/utils';
import withApi from 'app/utils/withApi';
-type QueryProps = Omit<TraceRequestProps, 'eventView'> & {
+type QueryProps = Omit<TraceRequestProps, 'eventId' | 'eventView'> & {
children: (props: TraceFullQueryChildrenProps) => React.ReactNode;
};
@@ -32,22 +30,15 @@ function EmptyTrace({children}: Pick<QueryProps, 'children'>) {
);
}
-function TraceFullQuery({event, children, ...props}: QueryProps) {
- // non transaction events are currently unsupported
- if (!isTransaction(event)) {
- return <EmptyTrace>{children}</EmptyTrace>;
- }
-
- const traceId = event.contexts?.trace?.trace_id;
+function TraceFullQuery({traceId, start, end, children, ...props}: QueryProps) {
if (!traceId) {
return <EmptyTrace>{children}</EmptyTrace>;
}
- const eventView = makeEventView(event);
+ const eventView = makeEventView(start, end);
return (
- <GenericDiscoverQuery<TraceFull, TraceProps>
- event={event}
+ <GenericDiscoverQuery<TraceFull, {}>
route={`events-trace/${traceId}`}
getRequestPayload={getQuickTraceRequestPayload}
beforeFetch={beforeFetch}
diff --git a/src/sentry/static/sentry/app/utils/performance/quickTrace/traceLiteQuery.tsx b/src/sentry/static/sentry/app/utils/performance/quickTrace/traceLiteQuery.tsx
index 292da17b707555..ca6ffb11a76e3d 100644
--- a/src/sentry/static/sentry/app/utils/performance/quickTrace/traceLiteQuery.tsx
+++ b/src/sentry/static/sentry/app/utils/performance/quickTrace/traceLiteQuery.tsx
@@ -1,16 +1,16 @@
import React from 'react';
-import GenericDiscoverQuery from 'app/utils/discover/genericDiscoverQuery';
+import GenericDiscoverQuery, {
+ DiscoverQueryProps,
+} from 'app/utils/discover/genericDiscoverQuery';
import {
TraceLite,
TraceLiteQueryChildrenProps,
- TraceProps,
TraceRequestProps,
} from 'app/utils/performance/quickTrace/types';
import {
beforeFetch,
getQuickTraceRequestPayload,
- isTransaction,
makeEventView,
} from 'app/utils/performance/quickTrace/utils';
import withApi from 'app/utils/withApi';
@@ -19,9 +19,12 @@ type QueryProps = Omit<TraceRequestProps, 'eventView'> & {
children: (props: TraceLiteQueryChildrenProps) => React.ReactNode;
};
-function getQuickTraceLiteRequestPayload({event, ...props}: TraceRequestProps) {
+function getQuickTraceLiteRequestPayload({
+ eventId,
+ ...props
+}: DiscoverQueryProps & Pick<TraceRequestProps, 'eventId'>) {
const additionalApiPayload = getQuickTraceRequestPayload(props);
- return Object.assign({event_id: event.id}, additionalApiPayload);
+ return Object.assign({event_id: eventId}, additionalApiPayload);
}
function EmptyTrace({children}: Pick<QueryProps, 'children'>) {
@@ -37,22 +40,15 @@ function EmptyTrace({children}: Pick<QueryProps, 'children'>) {
);
}
-function TraceLiteQuery({event, children, ...props}: QueryProps) {
- // non transaction events are currently unsupported
- if (!isTransaction(event)) {
- return <EmptyTrace>{children}</EmptyTrace>;
- }
-
- const traceId = event.contexts?.trace?.trace_id;
+function TraceLiteQuery({traceId, start, end, children, ...props}: QueryProps) {
if (!traceId) {
return <EmptyTrace>{children}</EmptyTrace>;
}
- const eventView = makeEventView(event);
+ const eventView = makeEventView(start, end);
return (
- <GenericDiscoverQuery<TraceLite, TraceProps>
- event={event}
+ <GenericDiscoverQuery<TraceLite, {eventId: string}>
route={`events-trace-light/${traceId}`}
getRequestPayload={getQuickTraceLiteRequestPayload}
beforeFetch={beforeFetch}
diff --git a/src/sentry/static/sentry/app/utils/performance/quickTrace/types.ts b/src/sentry/static/sentry/app/utils/performance/quickTrace/types.ts
index 8c3c7a666a6016..6a78c0a6a3aead 100644
--- a/src/sentry/static/sentry/app/utils/performance/quickTrace/types.ts
+++ b/src/sentry/static/sentry/app/utils/performance/quickTrace/types.ts
@@ -1,4 +1,3 @@
-import {Event} from 'app/types/event';
import {
DiscoverQueryProps,
GenericChildrenProps,
@@ -32,7 +31,10 @@ export type TraceFull = EventLite & {
};
export type TraceProps = {
- event: Event;
+ eventId: string;
+ traceId: string;
+ start: string;
+ end: string;
};
export type TraceRequestProps = DiscoverQueryProps & TraceProps;
diff --git a/src/sentry/static/sentry/app/utils/performance/quickTrace/utils.ts b/src/sentry/static/sentry/app/utils/performance/quickTrace/utils.ts
index 86a51df2229628..179f07542e19fe 100644
--- a/src/sentry/static/sentry/app/utils/performance/quickTrace/utils.ts
+++ b/src/sentry/static/sentry/app/utils/performance/quickTrace/utils.ts
@@ -1,7 +1,6 @@
import omit from 'lodash/omit';
import {Client} from 'app/api';
-import {getTraceDateTimeRange} from 'app/components/events/interfaces/spans/utils';
import {ALL_ACCESS_PROJECTS} from 'app/constants/globalSelectionHeader';
import {Event, EventTransaction} from 'app/types/event';
import EventView from 'app/utils/discover/eventView';
@@ -211,12 +210,7 @@ export function getQuickTraceRequestPayload({eventView, location}: DiscoverQuery
return omit(eventView.getEventsAPIPayload(location), ['field', 'sort', 'per_page']);
}
-export function makeEventView(event: EventTransaction) {
- const {start, end} = getTraceDateTimeRange({
- start: event.startTimestamp,
- end: event.endTimestamp,
- });
-
+export function makeEventView(start: string, end: string) {
return EventView.fromSavedQuery({
id: undefined,
version: 2,
@@ -232,3 +226,22 @@ export function makeEventView(event: EventTransaction) {
end,
});
}
+
+export function reduceTrace<T>(
+ trace: TraceFull,
+ visitor: (acc: T, e: TraceFull) => T,
+ initialValue: T
+): T {
+ let result = initialValue;
+
+ const events = [trace];
+ while (events.length) {
+ const current = events.pop()!;
+ for (const child of current.children) {
+ events.push(child);
+ }
+ result = visitor(result, current);
+ }
+
+ return result;
+}
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 9a9c3d46c781e4..e316788f83262d 100644
--- a/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx
+++ b/src/sentry/static/sentry/app/views/performance/traceDetails/content.tsx
@@ -1,11 +1,21 @@
import React from 'react';
import {Params} from 'react-router/lib/Router';
+import styled from '@emotion/styled';
+import * as Sentry from '@sentry/react';
import {Location} from 'history';
import * as Layout from 'app/components/layouts/thirds';
-import {t} from 'app/locale';
+import LoadingError from 'app/components/loadingError';
+import LoadingIndicator from 'app/components/loadingIndicator';
+import {t, tn} from 'app/locale';
+import space from 'app/styles/space';
import {Organization} from 'app/types';
+import TraceFullQuery from 'app/utils/performance/quickTrace/traceFullQuery';
+import {decodeScalar} from 'app/utils/queryString';
import Breadcrumb from 'app/views/performance/breadcrumb';
+import {MetaData} from 'app/views/performance/transactionDetails/styles';
+
+import {getTraceInfo} from './utils';
type Props = {
location: Location;
@@ -15,6 +25,74 @@ type Props = {
};
class TraceDetailsContent extends React.Component<Props> {
+ renderTraceLoading() {
+ return <LoadingIndicator />;
+ }
+
+ renderTraceRequiresDateRangeSelection() {
+ return <LoadingError message={t('Trace view requires a date range selection.')} />;
+ }
+
+ renderTraceNotFound() {
+ return <LoadingError message={t('The trace you are looking for was not found.')} />;
+ }
+
+ renderTrace(trace) {
+ const traceInfo = getTraceInfo(trace);
+
+ return (
+ <TraceDetailHeader>
+ <MetaData
+ headingText={t('Transactions')}
+ tooltipText={t('All the transactions that are a part of this trace.')}
+ bodyText={t(
+ '%s of %s',
+ traceInfo.relevantTransactions,
+ traceInfo.totalTransactions
+ )}
+ subtext={tn(
+ 'Across %s project',
+ 'Across %s projects',
+ traceInfo.relevantProjects
+ )}
+ />
+ </TraceDetailHeader>
+ );
+ }
+
+ renderContent() {
+ const {location, organization, traceSlug} = this.props;
+ const {query} = location;
+ const start = decodeScalar(query.start);
+ const end = decodeScalar(query.end);
+
+ if (!start || !end) {
+ Sentry.setTag('current.trace_id', traceSlug);
+ Sentry.captureException(new Error('No date range selection found.'));
+ return this.renderTraceRequiresDateRangeSelection();
+ }
+
+ return (
+ <TraceFullQuery
+ location={location}
+ orgSlug={organization.slug}
+ traceId={traceSlug}
+ start={start}
+ end={end}
+ >
+ {({isLoading, error, trace}) => {
+ if (isLoading) {
+ return this.renderTraceLoading();
+ } else if (error !== null || trace === null) {
+ return this.renderTraceNotFound();
+ } else {
+ return this.renderTrace(trace);
+ }
+ }}
+ </TraceFullQuery>
+ );
+ }
+
render() {
const {organization, location, traceSlug} = this.props;
@@ -33,11 +111,25 @@ class TraceDetailsContent extends React.Component<Props> {
</Layout.HeaderContent>
</Layout.Header>
<Layout.Body>
- <Layout.Main fullWidth>{null}</Layout.Main>
+ <Layout.Main fullWidth>{this.renderContent()}</Layout.Main>
</Layout.Body>
</React.Fragment>
);
}
}
+const TraceDetailHeader = styled('div')`
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ grid-template-rows: repeat(2, auto);
+ grid-gap: ${space(2)};
+ margin-bottom: ${space(2)};
+
+ @media (min-width: ${p => p.theme.breakpoints[1]}) {
+ grid-template-columns: minmax(160px, 1fr) minmax(160px, 1fr) minmax(160px, 1fr) 6fr;
+ grid-row-gap: 0;
+ margin-bottom: 0;
+ }
+`;
+
export default TraceDetailsContent;
diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/types.tsx b/src/sentry/static/sentry/app/views/performance/traceDetails/types.tsx
new file mode 100644
index 00000000000000..3bfb5e622927eb
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/performance/traceDetails/types.tsx
@@ -0,0 +1,18 @@
+export type TraceInfo = {
+ /**
+ * The total number projects in the trace.
+ */
+ totalProjects: number;
+ /**
+ * The number of projects in the trace that matched the user condition.
+ */
+ relevantProjects: number;
+ /**
+ * The total number transactions in the trace.
+ */
+ totalTransactions: number;
+ /**
+ * The number of transactions in the trace that matched the user condition.
+ */
+ relevantTransactions: number;
+};
diff --git a/src/sentry/static/sentry/app/views/performance/traceDetails/utils.ts b/src/sentry/static/sentry/app/views/performance/traceDetails/utils.ts
index 7b52161347e271..a6e6470bc5cee3 100644
--- a/src/sentry/static/sentry/app/views/performance/traceDetails/utils.ts
+++ b/src/sentry/static/sentry/app/views/performance/traceDetails/utils.ts
@@ -1,14 +1,52 @@
import {LocationDescriptor, Query} from 'history';
import {OrganizationSummary} from 'app/types';
+import {reduceTrace} from 'app/utils/performance/quickTrace/utils';
-export function getTraceSummaryUrl(
+import {TraceInfo} from './types';
+
+export function getTraceDetailsUrl(
organization: OrganizationSummary,
traceSlug: string,
+ start: string,
+ end: string,
query: Query
): LocationDescriptor {
return {
pathname: `/organizations/${organization.slug}/performance/trace/${traceSlug}/`,
- query: {...query},
+ query: {...query, start, end},
+ };
+}
+
+function traceVisitor() {
+ const projectIds = new Set();
+ const eventIds = new Set();
+
+ return (accumulator, event) => {
+ if (!projectIds.has(event.project_id)) {
+ projectIds.add(event.project_id);
+ accumulator.totalProjects += 1;
+
+ // No user conditions yet, so all projects are relevant.
+ accumulator.relevantProjects += 1;
+ }
+
+ if (!eventIds.has(event.event_id)) {
+ eventIds.add(event.event_id);
+ accumulator.totalTransactions += 1;
+
+ // No user conditions yet, so all transactions are relevant.
+ accumulator.relevantTransactions += 1;
+ }
+ return accumulator;
};
}
+
+export function getTraceInfo(trace) {
+ return reduceTrace<TraceInfo>(trace, traceVisitor(), {
+ totalProjects: 0,
+ relevantProjects: 0,
+ totalTransactions: 0,
+ relevantTransactions: 0,
+ });
+}
diff --git a/src/sentry/static/sentry/app/views/performance/transactionDetails/eventMetas.tsx b/src/sentry/static/sentry/app/views/performance/transactionDetails/eventMetas.tsx
index 7542424eb062aa..ab0cbe03e145c4 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionDetails/eventMetas.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionDetails/eventMetas.tsx
@@ -71,12 +71,14 @@ function EventMetas({event, organization, projectId, location, quickTrace}: Prop
bodyText={event.contexts?.trace?.status ?? '\u2014'}
subtext={httpStatus}
/>
- <QuickTrace
- event={event}
- organization={organization}
- location={location}
- quickTrace={quickTrace}
- />
+ <QuickTraceContainer>
+ <QuickTrace
+ event={event}
+ organization={organization}
+ location={location}
+ quickTrace={quickTrace}
+ />
+ </QuickTraceContainer>
</EventDetailHeader>
);
}
@@ -95,6 +97,16 @@ const EventDetailHeader = styled('div')`
}
`;
+const QuickTraceContainer = styled('div')`
+ grid-column: 1/4;
+
+ @media (min-width: ${p => p.theme.breakpoints[1]}) {
+ justify-self: flex-end;
+ min-width: 325px;
+ grid-column: unset;
+ }
+`;
+
function HttpStatus({event}: {event: Event}) {
const {tags} = event;
diff --git a/src/sentry/static/sentry/app/views/performance/transactionDetails/styles.tsx b/src/sentry/static/sentry/app/views/performance/transactionDetails/styles.tsx
index bb53be3a5e30fa..437a356e19adb7 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionDetails/styles.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionDetails/styles.tsx
@@ -36,18 +36,6 @@ export function MetaData({headingText, tooltipText, bodyText, subtext}: MetaData
const HeaderInfo = styled('div')`
height: 78px;
-
- &:last-child {
- grid-column: 1/4;
- }
-
- @media (min-width: ${p => p.theme.breakpoints[1]}) {
- &:last-child {
- justify-self: flex-end;
- min-width: 325px;
- grid-column: unset;
- }
- }
`;
const StyledSectionHeading = styled(SectionHeading)`
diff --git a/src/sentry/static/sentry/app/views/performance/transactionDetails/utils.tsx b/src/sentry/static/sentry/app/views/performance/transactionDetails/utils.tsx
index d7d233e9534fbb..4a9173ece0142f 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionDetails/utils.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionDetails/utils.tsx
@@ -9,7 +9,7 @@ import {generateEventSlug} from 'app/utils/discover/urls';
import {EventLite} from 'app/utils/performance/quickTrace/types';
import {QueryResults, stringifyQueryObject} from 'app/utils/tokenizeSearch';
-import {getTraceSummaryUrl} from '../traceDetails/utils';
+import {getTraceDetailsUrl} from '../traceDetails/utils';
import {getTransactionDetailsUrl} from '../utils';
export function generateSingleEventTarget(
@@ -74,14 +74,15 @@ export function generateTraceTarget(
): LocationDescriptor {
const traceId = event.contexts?.trace?.trace_id ?? '';
- if (organization.features.includes('trace-view-summary')) {
- return getTraceSummaryUrl(organization, traceId, {});
- }
-
const {start, end} = getTraceDateTimeRange({
start: event.startTimestamp,
end: event.endTimestamp,
});
+
+ if (organization.features.includes('trace-view-summary')) {
+ return getTraceDetailsUrl(organization, traceId, start, end, {});
+ }
+
const eventView = EventView.fromSavedQuery({
id: undefined,
name: `Transactions with Trace ID ${traceId}`,
|
ccbe8364a0b1285ab7a608a382348f1cc7b48f46
|
2021-05-14 06:35:41
|
Evan Purkhiser
|
fix(ui): BusinessIcon was using duplicate Ids causing problems (#26044)
| false
|
BusinessIcon was using duplicate Ids causing problems (#26044)
|
fix
|
diff --git a/static/app/icons/iconBusiness.tsx b/static/app/icons/iconBusiness.tsx
index 666a9ce8e0c1d8..ebb50f881c9a0f 100644
--- a/static/app/icons/iconBusiness.tsx
+++ b/static/app/icons/iconBusiness.tsx
@@ -2,6 +2,7 @@ import * as React from 'react';
import {keyframes, withTheme} from '@emotion/react';
import styled from '@emotion/styled';
+import {uniqueId} from 'app/utils/guid';
import {Theme} from 'app/utils/theme';
import SvgIcon from './svgIcon';
@@ -18,34 +19,38 @@ function IconBusinessComponent({
theme,
...props
}: WrappedProps) {
+ const uid = React.useMemo(() => uniqueId(), []);
+ const maskId = `icon-business-mask-${uid}`;
+ const gradientId = `icon-business-gradient-${uid}`;
+ const shineId = `icon-business-shine-${uid}`;
+
return (
<SvgIcon {...props} ref={forwardRef}>
- <mask id="icon-power-features-mask">
+ <mask id={maskId}>
<path
fill="white"
- id="power-feature"
d="M6.4 3.2001C3.7492 3.2001 1.6 5.3493 1.6 8.0001C1.6 10.6509 3.7492 12.8001 6.4 12.8001H9.6C12.2508 12.8001 14.4 10.6509 14.4 8.0001C14.4 5.3493 12.2508 3.2001 9.6 3.2001H6.4ZM6.4 1.6001H9.6C13.1348 1.6001 16 4.4653 16 8.0001C16 11.5349 13.1348 14.4001 9.6 14.4001H6.4C2.8652 14.4001 0 11.5349 0 8.0001C0 4.4653 2.8652 1.6001 6.4 1.6001ZM9.7128 3.6189L8.758 6.4161C8.7294 6.50034 8.73256 6.5921 8.76688 6.67418C8.8012 6.75622 8.86436 6.82294 8.9444 6.8617L10.8056 7.7721C10.8584 7.79754 10.9042 7.83534 10.9392 7.88226C10.9743 7.92922 10.9975 7.9839 11.007 8.0417C11.0164 8.09954 11.0117 8.15878 10.9934 8.21438C10.975 8.27002 10.9436 8.32042 10.9016 8.3613L6.592 12.5701C6.55684 12.6043 6.50968 12.6232 6.46068 12.6229C6.41168 12.6226 6.36472 12.6031 6.33 12.5685C6.30588 12.5445 6.28896 12.5143 6.2812 12.4812C6.2734 12.4481 6.27508 12.4135 6.286 12.3813L7.2416 9.5817C7.27016 9.49738 7.26688 9.40554 7.2324 9.32346C7.19792 9.24138 7.1346 9.17474 7.0544 9.1361L5.1944 8.2281C5.14156 8.20266 5.09564 8.16486 5.06056 8.1179C5.02544 8.07094 5.0022 8.01618 4.99276 7.9583C4.98336 7.90046 4.98804 7.84114 5.00644 7.78546C5.0248 7.72978 5.05636 7.67938 5.0984 7.6385L9.4068 3.4301C9.44196 3.39594 9.48912 3.37696 9.53812 3.37726C9.58716 3.37756 9.63408 3.39711 9.6688 3.4317C9.69292 3.45565 9.70984 3.4859 9.7176 3.519C9.7254 3.55209 9.72372 3.58671 9.7128 3.6189Z"
/>
</mask>
- <linearGradient id="icon-power-features-gradient">
+ <linearGradient id={gradientId}>
<stop offset="0%" stopColor={theme.businessIconColors[0]} />
<stop offset="100%" stopColor={theme.businessIconColors[1]} />
</linearGradient>
- <linearGradient id="icon-power-features-shine" gradientTransform="rotate(35)">
+ <linearGradient id={shineId} gradientTransform="rotate(35)">
<stop offset="0%" stopColor="rgba(255, 255, 255, 0)" />
<stop offset="50%" stopColor="rgba(255, 255, 255, 1)" />
<stop offset="100%" stopColor="rgba(255, 255, 255, 0)" />
</linearGradient>
<rect
- fill={gradient ? 'url(#icon-power-features-gradient)' : 'currentColor'}
- mask="url(#icon-power-features-mask)"
+ fill={gradient ? `url(#${gradientId})` : 'currentColor'}
+ mask={`url(#${maskId})`}
height="100%"
width="100%"
/>
{withShine && (
- <g mask="url(#icon-power-features-mask)">
- <ShineRect fill="url(#icon-power-features-shine" height="100%" width="100%" />
+ <g mask={`url(#${maskId})`}>
+ <ShineRect fill={`url(#${shineId})`} height="100%" width="100%" />
</g>
)}
</SvgIcon>
|
341f18ced0a83d4aa61fb31080451a1e82d9eb7d
|
2023-04-19 02:44:54
|
William Mak
|
feat(starfish): Rename operation to action (#47590)
| false
|
Rename operation to action (#47590)
|
feat
|
diff --git a/static/app/views/starfish/modules/databaseModule/databaseChartView.tsx b/static/app/views/starfish/modules/databaseModule/databaseChartView.tsx
index a324e30fa90cee..880a1e7cef5b43 100644
--- a/static/app/views/starfish/modules/databaseModule/databaseChartView.tsx
+++ b/static/app/views/starfish/modules/databaseModule/databaseChartView.tsx
@@ -13,15 +13,15 @@ type Props = {
export default function APIModuleView({}: Props) {
const GRAPH_QUERY = `
- select operation,
+ select action,
count() as count,
toStartOfInterval(start_timestamp, INTERVAL 1 DAY) as interval
from default.spans_experimental_starfish
where startsWith(span_operation, 'db')
and span_operation != 'db.redis'
group by interval,
- operation
- order by interval, operation
+ action
+ order by interval, action
`;
const TOP_QUERY = `
select quantile(0.5)(exclusive_time) as p50, description,
@@ -55,24 +55,24 @@ export default function APIModuleView({}: Props) {
initialData: [],
});
- const seriesByOperation: {[operation: string]: Series} = {};
+ const seriesByAction: {[action: string]: Series} = {};
graphData.forEach(datum => {
- seriesByOperation[datum.operation] = {
- seriesName: datum.operation,
+ seriesByAction[datum.action] = {
+ seriesName: datum.action,
data: [],
};
});
graphData.forEach(datum => {
- seriesByOperation[datum.operation].data.push({
+ seriesByAction[datum.action].data.push({
value: datum.count,
name: datum.interval,
});
});
- const data = Object.values(seriesByOperation);
+ const data = Object.values(seriesByAction);
- const seriesByQuery: {[operation: string]: Series} = {};
+ const seriesByQuery: {[action: string]: Series} = {};
topGraphData.forEach(datum => {
seriesByQuery[datum.description] = {
seriesName: datum.description.substring(0, 50),
diff --git a/static/app/views/starfish/modules/databaseModule/databaseTableView.tsx b/static/app/views/starfish/modules/databaseModule/databaseTableView.tsx
index 1fa435d3d9be15..c0966cf9e11ce6 100644
--- a/static/app/views/starfish/modules/databaseModule/databaseTableView.tsx
+++ b/static/app/views/starfish/modules/databaseModule/databaseTableView.tsx
@@ -6,8 +6,8 @@ import GridEditable, {GridColumnHeader} from 'sentry/components/gridEditable';
const HOST = 'http://localhost:8080';
type Props = {
+ action: string;
location: Location;
- operation: string;
transaction: string;
};
@@ -40,21 +40,21 @@ const COLUMN_ORDER = [
},
];
-export default function APIModuleView({location, operation, transaction}: Props) {
+export default function APIModuleView({location, action, transaction}: Props) {
const transactionFilter =
transaction.length > 0 ? `and transaction='${transaction}'` : '';
const ENDPOINT_QUERY = `select description as desc, (divide(count(), divide(1209600.0, 60)) AS epm), quantile(0.75)(exclusive_time) as p75,
uniq(transaction) as transactions,
sum(exclusive_time) as total_time
from default.spans_experimental_starfish
- where startsWith(span_operation, 'db') and span_operation != 'db.redis' and operation='${operation}' ${transactionFilter}
+ where startsWith(span_operation, 'db') and span_operation != 'db.redis' and action='${action}' ${transactionFilter}
group by description
order by -pow(10, floor(log10(count()))), -quantile(0.5)(exclusive_time)
limit 100
`;
const {isLoading: areEndpointsLoading, data: endpointsData} = useQuery({
- queryKey: ['endpoints', operation, transaction],
+ queryKey: ['endpoints', action, transaction],
queryFn: () => fetch(`${HOST}/?query=${ENDPOINT_QUERY}`).then(res => res.json()),
retry: false,
initialData: [],
diff --git a/static/app/views/starfish/modules/databaseModule/index.tsx b/static/app/views/starfish/modules/databaseModule/index.tsx
index 12b73aee355437..3c8c4b10c5d168 100644
--- a/static/app/views/starfish/modules/databaseModule/index.tsx
+++ b/static/app/views/starfish/modules/databaseModule/index.tsx
@@ -34,28 +34,28 @@ function getOptions() {
'UPDATE',
'connect',
'delete',
- ].map(operation => {
+ ].map(action => {
return {
- value: operation,
+ value: action,
prefix,
- label: operation,
+ label: action,
};
});
}
type State = {
- operation: string;
+ action: string;
transaction: string;
};
class DatabaseModule extends Component<Props, State> {
state: State = {
- operation: 'SELECT',
+ action: 'SELECT',
transaction: '',
};
handleOptionChange(value) {
- this.setState({operation: value});
+ this.setState({action: value});
}
handleSearch(query) {
@@ -74,7 +74,7 @@ class DatabaseModule extends Component<Props, State> {
render() {
const {location, organization} = this.props;
- const {operation, transaction} = this.state;
+ const {action, transaction} = this.state;
const eventView = EventView.fromLocation(location);
return (
@@ -91,7 +91,7 @@ class DatabaseModule extends Component<Props, State> {
<PageErrorAlert />
<DatabaseChartView location={location} />
<CompactSelect
- value={operation}
+ value={action}
options={getOptions()}
onChange={opt => this.handleOptionChange(opt.value)}
/>
@@ -103,7 +103,7 @@ class DatabaseModule extends Component<Props, State> {
/>
<DatabaseTableView
location={location}
- operation={operation}
+ action={action}
transaction={transaction}
/>
</Layout.Main>
|
4f628a7106c1630732228147b030ebd49e17d314
|
2022-09-29 21:50:54
|
Kev
|
fix(perf-issues): Need to splat array in span evidence (#39465)
| false
|
Need to splat array in span evidence (#39465)
|
fix
|
diff --git a/static/app/components/events/interfaces/performance/spanEvidence.tsx b/static/app/components/events/interfaces/performance/spanEvidence.tsx
index 668183416a312d..b3dd6abf612772 100644
--- a/static/app/components/events/interfaces/performance/spanEvidence.tsx
+++ b/static/app/components/events/interfaces/performance/spanEvidence.tsx
@@ -41,7 +41,7 @@ export function SpanEvidenceSection({event, organization}: Props) {
const spanEntry = event.entries.find((entry: SpanEntry | any): entry is SpanEntry => {
return entry.type === EntryType.SPANS;
});
- const spans: Array<RawSpanType | TraceContextSpanProxy> = spanEntry?.data ?? [];
+ const spans: Array<RawSpanType | TraceContextSpanProxy> = [...spanEntry?.data] ?? [];
if (event?.contexts?.trace && event?.contexts?.trace?.span_id) {
// TODO: Fix this conditional and check if span_id is ever actually undefined.
|
bace0d5dfd18749125f7695e998fc2027710d1c2
|
2024-12-24 03:20:42
|
Scott Cooper
|
fix(issues): Prevent tag drawer overflow w/ long tags (#82545)
| false
|
Prevent tag drawer overflow w/ long tags (#82545)
|
fix
|
diff --git a/static/app/components/events/eventDrawer.tsx b/static/app/components/events/eventDrawer.tsx
index 59dd58926a59ec..fb26d789b2c55f 100644
--- a/static/app/components/events/eventDrawer.tsx
+++ b/static/app/components/events/eventDrawer.tsx
@@ -47,6 +47,9 @@ export const EventDrawerHeader = styled(DrawerHeader)`
max-height: ${MIN_NAV_HEIGHT}px;
box-shadow: none;
border-bottom: 1px solid ${p => p.theme.border};
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 100%;
`;
export const EventNavigator = styled('div')`
diff --git a/static/app/views/issueDetails/groupTags/groupTagsDrawer.tsx b/static/app/views/issueDetails/groupTags/groupTagsDrawer.tsx
index 38dcb40b115316..1c7d9dcef4b5a6 100644
--- a/static/app/views/issueDetails/groupTags/groupTagsDrawer.tsx
+++ b/static/app/views/issueDetails/groupTags/groupTagsDrawer.tsx
@@ -12,7 +12,6 @@ import {
EventDrawerContainer,
EventDrawerHeader,
EventNavigator,
- Header,
NavigationCrumbs,
SearchInput,
ShortId,
@@ -211,3 +210,10 @@ const Container = styled('div')`
gap: ${space(2)};
margin-bottom: ${space(2)};
`;
+
+const Header = styled('h3')`
+ ${p => p.theme.overflowEllipsis};
+ font-size: ${p => p.theme.fontSizeExtraLarge};
+ font-weight: ${p => p.theme.fontWeightBold};
+ margin: 0;
+`;
|
6a7a162523397e7aa7261da9d3efdf42492ba15c
|
2023-01-20 14:02:46
|
Joris Bayer
|
chore(txnames): Unite feature flags (#43429)
| false
|
Unite feature flags (#43429)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 1769eb98b42417..4a2f488977bfc9 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1057,7 +1057,7 @@ def SOCIAL_AUTH_DEFAULT_USERNAME():
# Try to derive normalization rules by clustering transaction names.
"organizations:transaction-name-clusterer": False,
# Sanitize transaction names in the ingestion pipeline.
- "organizations:transaction-name-sanitization": False,
+ "organizations:transaction-name-sanitization": False, # DEPRECATED
# Extraction metrics for transactions during ingestion.
"organizations:transaction-metrics-extraction": False,
# True if release-health related queries should be run against both
diff --git a/src/sentry/relay/config/__init__.py b/src/sentry/relay/config/__init__.py
index 370950473115b0..9f459960f07bfe 100644
--- a/src/sentry/relay/config/__init__.py
+++ b/src/sentry/relay/config/__init__.py
@@ -182,7 +182,7 @@ class TransactionNameRule(TypedDict):
def get_transaction_names_config(project: Project) -> Optional[Sequence[TransactionNameRule]]:
- if not features.has("organizations:transaction-name-sanitization", project.organization):
+ if not features.has("organizations:transaction-name-normalize", project.organization):
return None
cluster_rules = get_sorted_rules(project)
diff --git a/tests/sentry/ingest/test_transaction_clusterer.py b/tests/sentry/ingest/test_transaction_clusterer.py
index fe6bb4f7be29b3..3bbeea68f8637d 100644
--- a/tests/sentry/ingest/test_transaction_clusterer.py
+++ b/tests/sentry/ingest/test_transaction_clusterer.py
@@ -222,18 +222,19 @@ def _get_projconfig_tx_rules(project: Project):
get_project_config(project, full_config=True).to_dict().get("config").get("txNameRules")
)
- with Feature({"organizations:transaction-name-sanitization": False}):
+ feature = "organizations:transaction-name-normalize"
+ with Feature({feature: False}):
assert _get_projconfig_tx_rules(default_project) is None
- with Feature({"organizations:transaction-name-sanitization": True}):
+ with Feature({feature: True}):
assert _get_projconfig_tx_rules(default_project) is None
default_project.update_option(
"sentry:transaction_name_cluster_rules", [("/rule/*/0/**", 0), ("/rule/*/1/**", 1)]
)
- with Feature({"organizations:transaction-name-sanitization": False}):
+ with Feature({feature: False}):
assert _get_projconfig_tx_rules(default_project) is None
- with Feature({"organizations:transaction-name-sanitization": True}):
+ with Feature({feature: True}):
assert _get_projconfig_tx_rules(default_project) == [
# TTL is 90d, so three months to expire
{
|
12236c6c1684d92b3043750537a1073c241ae3ed
|
2024-04-22 20:31:09
|
Philipp Hofmann
|
fix(sdk-crashes): Fix sample rate (#69406)
| false
|
Fix sample rate (#69406)
|
fix
|
diff --git a/src/sentry/utils/sdk_crashes/sdk_crash_detection.py b/src/sentry/utils/sdk_crashes/sdk_crash_detection.py
index 2a44ef999ac417..83cb825319286e 100644
--- a/src/sentry/utils/sdk_crashes/sdk_crash_detection.py
+++ b/src/sentry/utils/sdk_crashes/sdk_crash_detection.py
@@ -108,8 +108,8 @@ def detect_sdk_crash(
metrics.incr("post_process.sdk_crash_monitoring.detecting_sdk_crash", tags=metric_tags)
if sdk_crash_detector.is_sdk_crash(frames):
- # TODO this rollout rate is backwards
- if random.random() >= sample_rate:
+ # The sample rate is backwards on purpose, because we return None if we don't want to sample an event.
+ if random.random() > sample_rate:
return None
sdk_crash_event_data = strip_event_data(event.data, sdk_crash_detector)
diff --git a/tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py b/tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py
index 52d9eb356afbbb..198829223727d2 100644
--- a/tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py
+++ b/tests/sentry/utils/sdk_crashes/test_sdk_crash_detection.py
@@ -172,42 +172,37 @@ def create_event(self, data, project_id, assert_no_errors=True):
return self.store_event(data=data, project_id=project_id, assert_no_errors=assert_no_errors)
[email protected](
+ ["sample_rate", "random_value", "sampled"],
+ [
+ (0.0, 0.0001, False),
+ (0.0, 0.5, False),
+ (1.0, 0.0001, True),
+ (1.0, 0.9999, True),
+ (0.1, 0.0001, True),
+ (0.1, 0.09, True),
+ (0.1, 0.1, True),
+ (0.1, 0.11, False),
+ (0.1, 0.5, False),
+ (0.1, 0.999, False),
+ ],
+)
@django_db_all
@pytest.mark.snuba
-@patch("random.random", return_value=0.0)
-@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
-def test_sample_is_rate_zero(mock_sdk_crash_reporter, mock_random, store_event):
- event = store_event(data=get_crash_event())
-
- configs = build_sdk_configs()
- configs[0].sample_rate = 0.0
-
- sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
-
- assert mock_sdk_crash_reporter.report.call_count == 0
-
-
-@django_db_all
[email protected]
-@patch("random.random", return_value=0.1)
@patch("sentry.utils.sdk_crashes.sdk_crash_detection.sdk_crash_detection.sdk_crash_reporter")
-def test_sampling_rate(mock_sdk_crash_reporter, mock_random, store_event):
+def test_sample_rate(mock_sdk_crash_reporter, store_event, sample_rate, random_value, sampled):
event = store_event(data=get_crash_event())
- configs = build_sdk_configs()
-
- # not sampled
- configs[0].sample_rate = 0.09
- sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
-
- configs[0].sample_rate = 0.1
- sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
+ with patch("random.random", return_value=random_value):
+ configs = build_sdk_configs()
+ configs[0].sample_rate = sample_rate
- # sampled
- configs[0].sample_rate = 0.11
- sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
+ sdk_crash_detection.detect_sdk_crash(event=event, configs=configs)
- assert mock_sdk_crash_reporter.report.call_count == 1
+ if sampled:
+ assert mock_sdk_crash_reporter.report.call_count == 1
+ else:
+ assert mock_sdk_crash_reporter.report.call_count == 0
@django_db_all
|
7c092ae2b11f979c95d84b3e0e24dff182ecd919
|
2022-05-23 12:50:42
|
Evan Purkhiser
|
ref(js): Simplify PageHeading Props type (#34892)
| false
|
Simplify PageHeading Props type (#34892)
|
ref
|
diff --git a/static/app/components/pageHeading.tsx b/static/app/components/pageHeading.tsx
index f4045e213ce248..c14acd3a7a16e8 100644
--- a/static/app/components/pageHeading.tsx
+++ b/static/app/components/pageHeading.tsx
@@ -2,13 +2,7 @@ import styled from '@emotion/styled';
import space from 'sentry/styles/space';
-type Props = {
- children: React.ReactNode;
- className?: string;
- withMargins?: boolean;
-};
-
-const PageHeading = styled('h1')<Props>`
+const PageHeading = styled('h1')<{withMargins?: boolean}>`
${p => p.theme.text.pageTitle};
color: ${p => p.theme.headingColor};
margin: 0;
|
b5ecab101fe502931bf9002fb1702c7d9cac4abe
|
2024-07-24 00:18:37
|
Katie Byers
|
feat(utils): Add core `CircuitBreaker` functionality (#74560)
| false
|
Add core `CircuitBreaker` functionality (#74560)
|
feat
|
diff --git a/src/sentry/utils/circuit_breaker2.py b/src/sentry/utils/circuit_breaker2.py
index 108349f3189a9f..cbf870d50137a4 100644
--- a/src/sentry/utils/circuit_breaker2.py
+++ b/src/sentry/utils/circuit_breaker2.py
@@ -12,7 +12,12 @@
from django.conf import settings
-from sentry.ratelimits.sliding_windows import Quota, RedisSlidingWindowRateLimiter, RequestedQuota
+from sentry.ratelimits.sliding_windows import (
+ GrantedQuota,
+ Quota,
+ RedisSlidingWindowRateLimiter,
+ RequestedQuota,
+)
logger = logging.getLogger(__name__)
@@ -182,6 +187,96 @@ def __init__(self, key: str, config: CircuitBreakerConfig):
)
self.recovery_duration = default_recovery_duration
+ def record_error(self) -> None:
+ """
+ Record a single error towards the breaker's quota, and handle the case where that error puts
+ us over the limit.
+ """
+ now = int(time.time())
+ state, seconds_left_in_state = self._get_state_and_remaining_time()
+
+ if state == CircuitBreakerState.BROKEN:
+ assert seconds_left_in_state is not None # mypy appeasement
+
+ # If the circuit is BROKEN, and `should_allow_request` is being used correctly, requests
+ # should be blocked and we shouldn't even be here. That said, maybe there was a race
+ # condition, so make sure the circuit hasn't just been tripped before crying foul.
+ seconds_elapsed_in_state = self.broken_state_duration - seconds_left_in_state
+ if seconds_elapsed_in_state > 5:
+ logger.warning(
+ "Attempt to record circuit breaker error while circuit is in BROKEN state",
+ extra={"key": self.key, "time_in_state": seconds_elapsed_in_state},
+ )
+ # We shouldn't have made the request, so don't record the error
+ return
+
+ # Even though we're not checking it during RECOVERY, we track errors in the primary quota as
+ # well as in the RECOVERY quota because they still happened, and eventually switching back
+ # to the okay state doesn't make that untrue
+ quotas = (
+ [self.primary_quota, self.recovery_quota]
+ if state == CircuitBreakerState.RECOVERY
+ else [self.primary_quota]
+ )
+ self.limiter.use_quotas(
+ [RequestedQuota(self.key, 1, quotas)], [GrantedQuota(self.key, 1, [])], now
+ )
+
+ # If incrementing has made us hit the current limit, switch to the BROKEN state
+ controlling_quota = self._get_controlling_quota(state)
+ remaining_errors_allowed = self._get_remaining_error_quota(controlling_quota)
+ if remaining_errors_allowed == 0:
+ logger.warning(
+ "Circuit breaker '%s' error limit hit",
+ self.key,
+ extra={
+ "current_state": state,
+ "error_limit": controlling_quota.limit,
+ "error_limit_window": controlling_quota.window_seconds,
+ },
+ )
+
+ # RECOVERY will only start after the BROKEN state has expired, so push out the RECOVERY
+ # expiry time. We'll store the expiry times as our redis values so we can determine how
+ # long we've been in a given state.
+ broken_state_timeout = self.broken_state_duration
+ recovery_state_timeout = self.broken_state_duration + self.recovery_duration
+ broken_state_expiry = now + broken_state_timeout
+ recovery_state_expiry = now + recovery_state_timeout
+
+ # Set reids keys for switching state. While they're both set (starting now) we'll be in
+ # the BROKEN state. Once `broken_state_key` expires in redis we'll switch to RECOVERY,
+ # and then once `recovery_state_key` expires we'll be back to normal.
+ try:
+ self._set_in_redis(
+ [
+ (self.broken_state_key, broken_state_expiry, broken_state_timeout),
+ (self.recovery_state_key, recovery_state_expiry, recovery_state_timeout),
+ ]
+ )
+
+ # If redis errors, stay in the current state
+ except Exception:
+ logger.exception(
+ "Couldn't set state-change keys in redis for circuit breaker '%s'",
+ self.key,
+ extra={"current_state": state},
+ )
+
+ def should_allow_request(self) -> bool:
+ """
+ Determine, based on the current state of the breaker and the number of allowable errors
+ remaining, whether requests should be allowed through.
+ """
+ state, _ = self._get_state_and_remaining_time()
+
+ if state == CircuitBreakerState.BROKEN:
+ return False
+
+ controlling_quota = self._get_controlling_quota(state)
+
+ return self._get_remaining_error_quota(controlling_quota) > 0
+
def _get_from_redis(self, keys: list[str]) -> Any:
for key in keys:
self.redis_pipeline.get(key)
diff --git a/tests/sentry/utils/test_circuit_breaker2.py b/tests/sentry/utils/test_circuit_breaker2.py
index 5cb4370b09e304..f4bd79f0c99c84 100644
--- a/tests/sentry/utils/test_circuit_breaker2.py
+++ b/tests/sentry/utils/test_circuit_breaker2.py
@@ -3,6 +3,7 @@
from unittest import TestCase
from unittest.mock import ANY, MagicMock, patch
+import time_machine
from django.conf import settings
from redis.client import Pipeline
@@ -318,3 +319,225 @@ def test_fixes_mismatched_state_durations(self, mock_logger: MagicMock):
500,
)
assert breaker.recovery_duration == 500
+
+
+@freeze_time()
+class RecordErrorTest(TestCase):
+ def setUp(self) -> None:
+ self.config = DEFAULT_CONFIG
+ self.breaker = MockCircuitBreaker("dogs_are_great", self.config)
+
+ # Clear all existing keys from redis
+ self.breaker.redis_pipeline.flushall()
+ self.breaker.redis_pipeline.execute()
+
+ def test_increments_error_count(self):
+ config = self.config
+ breaker = self.breaker
+
+ # The breaker starts with a clean slate
+ assert breaker._get_remaining_error_quota() == config["error_limit"]
+
+ breaker.record_error()
+
+ # The error has been tallied
+ assert breaker._get_remaining_error_quota() == config["error_limit"] - 1
+
+ def test_no_error_recorded_in_broken_state(self):
+ breaker = self.breaker
+
+ breaker._set_breaker_state(CircuitBreakerState.BROKEN)
+ breaker._add_quota_usage(breaker.primary_quota, breaker.error_limit)
+
+ # Because we're in the BROKEN state, we start with the main quota maxed out and the
+ # RECOVERY quota yet to be used
+ assert breaker._get_remaining_error_quota(breaker.primary_quota) == 0
+ assert (
+ breaker._get_remaining_error_quota(breaker.recovery_quota)
+ == breaker.recovery_error_limit
+ )
+
+ breaker.record_error()
+
+ # Neither quota is incremented
+ assert breaker._get_remaining_error_quota(breaker.primary_quota) == 0
+ assert (
+ breaker._get_remaining_error_quota(breaker.recovery_quota)
+ == breaker.recovery_error_limit
+ )
+
+ @patch("sentry.utils.circuit_breaker2.logger")
+ def test_logs_a_warning_in_broken_state(self, mock_logger: MagicMock):
+ breaker = self.breaker
+
+ seconds_ellapsed_since_circuit_break = 2
+ breaker._set_breaker_state(
+ CircuitBreakerState.BROKEN,
+ seconds_left=breaker.broken_state_duration - seconds_ellapsed_since_circuit_break,
+ )
+
+ breaker.record_error()
+
+ # No log - we just switched into BROKEN state, and even though we're not supposed to land in
+ # the `record_error` method in that state, there's a small buffer to account for race
+ # conditions
+ assert mock_logger.warning.call_count == 0
+
+ seconds_ellapsed_since_circuit_break = 20
+ breaker._set_breaker_state(
+ CircuitBreakerState.BROKEN,
+ seconds_left=breaker.broken_state_duration - seconds_ellapsed_since_circuit_break,
+ )
+
+ breaker.record_error()
+
+ # Now we do log a warning, because at this point we can no longer blame a race condition -
+ # it's been too long since the circuit broke
+ mock_logger.warning.assert_called_with(
+ "Attempt to record circuit breaker error while circuit is in BROKEN state",
+ extra={"key": "dogs_are_great", "time_in_state": 20},
+ )
+
+ @patch("sentry.utils.circuit_breaker2.logger")
+ def test_handles_hitting_max_errors_in_non_broken_state(self, mock_logger: MagicMock):
+ config = self.config
+ breaker = self.breaker
+ now = int(time.time())
+
+ for state, quota, limit in [
+ (CircuitBreakerState.OK, breaker.primary_quota, breaker.error_limit),
+ (CircuitBreakerState.RECOVERY, breaker.recovery_quota, breaker.recovery_error_limit),
+ ]:
+
+ breaker._set_breaker_state(state)
+ breaker._add_quota_usage(quota, limit - 1)
+ assert breaker._get_remaining_error_quota(quota) == 1
+ assert breaker._get_controlling_quota() == quota
+
+ breaker.record_error()
+
+ # Hitting the limit puts us into the BROKEN state
+ assert breaker._get_remaining_error_quota(quota) == 0
+ assert breaker._get_controlling_quota() is None
+ assert breaker._get_state_and_remaining_time() == (
+ CircuitBreakerState.BROKEN,
+ breaker.broken_state_duration,
+ )
+ mock_logger.warning.assert_called_with(
+ "Circuit breaker '%s' error limit hit",
+ "dogs_are_great",
+ extra={
+ "current_state": state,
+ "error_limit": limit,
+ "error_limit_window": config["error_limit_window"],
+ },
+ )
+
+ # Now jump to one second after the BROKEN state has expired to see that we're in
+ # RECOVERY
+ with time_machine.travel(now + breaker.broken_state_duration + 1, tick=False):
+ assert breaker._get_controlling_quota() is breaker.recovery_quota
+ assert breaker._get_state_and_remaining_time() == (
+ CircuitBreakerState.RECOVERY,
+ breaker.recovery_duration - 1,
+ )
+
+ @patch("sentry.utils.circuit_breaker2.logger")
+ def test_stays_in_current_state_if_redis_call_changing_state_fails(
+ self, mock_logger: MagicMock
+ ):
+ breaker = self.breaker
+
+ for current_state, quota, limit, seconds_left in [
+ # The case where the current state is the BROKEN state isn't included here because the
+ # switch from BROKEN state to RECOVERY state happens passively (by `broken_state_key`
+ # expiring), rather than through an active call to redis
+ (
+ CircuitBreakerState.OK,
+ breaker.primary_quota,
+ breaker.error_limit,
+ None,
+ ),
+ (
+ CircuitBreakerState.RECOVERY,
+ breaker.recovery_quota,
+ breaker.recovery_error_limit,
+ 1231,
+ ),
+ ]:
+
+ breaker._set_breaker_state(current_state, seconds_left)
+ breaker._add_quota_usage(quota, limit - 1)
+ assert breaker._get_remaining_error_quota(quota) == 1
+ assert breaker._get_controlling_quota() == quota
+
+ with patch(
+ "sentry.utils.circuit_breaker2.CircuitBreaker._set_in_redis", side_effect=Exception
+ ):
+ breaker.record_error()
+
+ # We've recorded the error, but the state hasn't changed
+ assert breaker._get_remaining_error_quota(quota) == 0
+ assert breaker._get_controlling_quota() == quota
+ assert breaker._get_state_and_remaining_time() == (current_state, seconds_left)
+ mock_logger.exception.assert_called_with(
+ "Couldn't set state-change keys in redis for circuit breaker '%s'",
+ breaker.key,
+ extra={"current_state": current_state},
+ )
+
+
+@freeze_time()
+class ShouldAllowRequestTest(TestCase):
+ def setUp(self) -> None:
+ self.config = DEFAULT_CONFIG
+ self.breaker = MockCircuitBreaker("dogs_are_great", self.config)
+
+ # Clear all existing keys from redis
+ self.breaker.redis_pipeline.flushall()
+ self.breaker.redis_pipeline.execute()
+
+ def test_allows_request_in_non_broken_state_with_quota_remaining(self):
+ breaker = self.breaker
+
+ for state, quota, limit in [
+ (CircuitBreakerState.OK, breaker.primary_quota, breaker.error_limit),
+ (CircuitBreakerState.RECOVERY, breaker.recovery_quota, breaker.recovery_error_limit),
+ ]:
+ breaker._set_breaker_state(state)
+ breaker._add_quota_usage(quota, limit - 5)
+ assert breaker._get_remaining_error_quota(quota) == 5
+
+ assert breaker.should_allow_request() is True
+
+ def test_blocks_request_in_non_broken_state_with_no_quota_remaining(self):
+ breaker = self.breaker
+
+ for state, quota, limit in [
+ (CircuitBreakerState.OK, breaker.primary_quota, breaker.error_limit),
+ (CircuitBreakerState.RECOVERY, breaker.recovery_quota, breaker.recovery_error_limit),
+ ]:
+ breaker._set_breaker_state(state)
+ breaker._add_quota_usage(quota, limit)
+ assert breaker._get_remaining_error_quota(quota) == 0
+
+ assert breaker.should_allow_request() is False
+
+ def test_blocks_request_in_BROKEN_state(self):
+ breaker = self.breaker
+
+ breaker._set_breaker_state(CircuitBreakerState.BROKEN)
+
+ assert breaker.should_allow_request() is False
+
+ @patch("sentry.utils.circuit_breaker2.logger")
+ def test_allows_request_if_redis_call_fails(self, mock_logger: MagicMock):
+ breaker = self.breaker
+
+ with patch(
+ "sentry.utils.circuit_breaker2.CircuitBreaker._get_from_redis", side_effect=Exception
+ ):
+ assert breaker.should_allow_request() is True
+ mock_logger.exception.assert_called_with(
+ "Couldn't get state from redis for circuit breaker '%s'", breaker.key
+ )
|
fd9cb1cba8235d0313db20217190bce67b8297c3
|
2023-08-10 00:57:34
|
Michelle Zhang
|
ref(replays): adjust widget tooltips and headers (#54298)
| false
|
adjust widget tooltips and headers (#54298)
|
ref
|
diff --git a/static/app/views/replays/list/replaysErroneousDeadRageCards.tsx b/static/app/views/replays/list/replaysErroneousDeadRageCards.tsx
index 0efe0b043adc3b..45e20db6daa434 100644
--- a/static/app/views/replays/list/replaysErroneousDeadRageCards.tsx
+++ b/static/app/views/replays/list/replaysErroneousDeadRageCards.tsx
@@ -101,9 +101,15 @@ function ReplaysErroneousDeadRageCards() {
const hasDeadRageCards = organization.features.includes('replay-error-click-cards');
const {hasSentOneReplay, fetching} = useHaveSelectedProjectsSentAnyReplayEvents();
- const deadCols = [ReplayColumn.MOST_DEAD_CLICKS, ReplayColumn.COUNT_DEAD_CLICKS];
-
- const rageCols = [ReplayColumn.MOST_RAGE_CLICKS, ReplayColumn.COUNT_RAGE_CLICKS];
+ const deadCols = [
+ ReplayColumn.MOST_DEAD_CLICKS,
+ ReplayColumn.COUNT_DEAD_CLICKS_NO_HEADER,
+ ];
+
+ const rageCols = [
+ ReplayColumn.MOST_RAGE_CLICKS,
+ ReplayColumn.COUNT_RAGE_CLICKS_NO_HEADER,
+ ];
return hasSessionReplay && hasDeadRageCards && hasSentOneReplay && !fetching ? (
<SplitCardContainer>
diff --git a/static/app/views/replays/replayTable/headerCell.tsx b/static/app/views/replays/replayTable/headerCell.tsx
index d325d80eb76f5b..ba6d00ce3be251 100644
--- a/static/app/views/replays/replayTable/headerCell.tsx
+++ b/static/app/views/replays/replayTable/headerCell.tsx
@@ -43,6 +43,9 @@ function HeaderCell({column, sort}: Props) {
/>
);
+ case ReplayColumn.COUNT_DEAD_CLICKS_NO_HEADER:
+ return <SortableHeader label="" />;
+
case ReplayColumn.COUNT_ERRORS:
return <SortableHeader sort={sort} fieldName="count_errors" label={t('Errors')} />;
@@ -62,6 +65,9 @@ function HeaderCell({column, sort}: Props) {
/>
);
+ case ReplayColumn.COUNT_RAGE_CLICKS_NO_HEADER:
+ return <SortableHeader label="" />;
+
case ReplayColumn.DURATION:
return <SortableHeader sort={sort} fieldName="duration" label={t('Duration')} />;
@@ -75,10 +81,32 @@ function HeaderCell({column, sort}: Props) {
return <SortableHeader label={t('Most erroneous replays')} />;
case ReplayColumn.MOST_RAGE_CLICKS:
- return <SortableHeader label={t('Most rage clicks')} />;
+ return (
+ <SortableHeader
+ label={t('Most rage clicks')}
+ tooltip={tct(
+ 'A rage click is 5 or more clicks on a dead element, which exhibits no page activity after 7 seconds. Requires SDK version >= [minSDK]. [link:Learn more.]',
+ {
+ minSDK: MIN_DEAD_RAGE_CLICK_SDK,
+ link: <ExternalLink href="https://docs.sentry.io/platforms/javascript/" />,
+ }
+ )}
+ />
+ );
case ReplayColumn.MOST_DEAD_CLICKS:
- return <SortableHeader label={t('Most dead clicks')} />;
+ return (
+ <SortableHeader
+ label={t('Most dead clicks')}
+ tooltip={tct(
+ 'A dead click is a user click that does not result in any page activity after 7 seconds. Requires SDK version >= [minSDK]. [link:Learn more.]',
+ {
+ minSDK: MIN_DEAD_RAGE_CLICK_SDK,
+ link: <ExternalLink href="https://docs.sentry.io/platforms/javascript/" />,
+ }
+ )}
+ />
+ );
case ReplayColumn.SLOWEST_TRANSACTION:
return (
diff --git a/static/app/views/replays/replayTable/index.tsx b/static/app/views/replays/replayTable/index.tsx
index 34255382551bb9..c0155ba5a296a4 100644
--- a/static/app/views/replays/replayTable/index.tsx
+++ b/static/app/views/replays/replayTable/index.tsx
@@ -158,12 +158,18 @@ function ReplayTable({
case ReplayColumn.COUNT_DEAD_CLICKS:
return <DeadClickCountCell key="countDeadClicks" replay={replay} />;
+ case ReplayColumn.COUNT_DEAD_CLICKS_NO_HEADER:
+ return <DeadClickCountCell key="countDeadClicks" replay={replay} />;
+
case ReplayColumn.COUNT_ERRORS:
return <ErrorCountCell key="countErrors" replay={replay} />;
case ReplayColumn.COUNT_RAGE_CLICKS:
return <RageClickCountCell key="countRageClicks" replay={replay} />;
+ case ReplayColumn.COUNT_RAGE_CLICKS_NO_HEADER:
+ return <RageClickCountCell key="countRageClicks" replay={replay} />;
+
case ReplayColumn.DURATION:
return <DurationCell key="duration" replay={replay} />;
diff --git a/static/app/views/replays/replayTable/tableCell.tsx b/static/app/views/replays/replayTable/tableCell.tsx
index 6a6be4dce2935d..0bfae5fae7a988 100644
--- a/static/app/views/replays/replayTable/tableCell.tsx
+++ b/static/app/views/replays/replayTable/tableCell.tsx
@@ -277,7 +277,7 @@ export function RageClickCountCell({replay}: Props) {
return (
<Item data-test-id="replay-table-count-rage-clicks">
{replay.count_rage_clicks ? (
- <Count>{replay.count_rage_clicks}</Count>
+ <DeadRageCount>{replay.count_rage_clicks}</DeadRageCount>
) : (
<Count>0</Count>
)}
@@ -292,7 +292,7 @@ export function DeadClickCountCell({replay}: Props) {
return (
<Item data-test-id="replay-table-count-dead-clicks">
{replay.count_dead_clicks ? (
- <Count>{replay.count_dead_clicks}</Count>
+ <DeadRageCount>{replay.count_dead_clicks}</DeadRageCount>
) : (
<Count>0</Count>
)}
@@ -347,6 +347,11 @@ const Count = styled('span')`
font-variant-numeric: tabular-nums;
`;
+const DeadRageCount = styled(Count)`
+ display: flex;
+ width: 40px;
+`;
+
const ErrorCount = styled(Count)`
display: flex;
align-items: center;
diff --git a/static/app/views/replays/replayTable/types.tsx b/static/app/views/replays/replayTable/types.tsx
index 072c429c03ae28..bef494b2c286bf 100644
--- a/static/app/views/replays/replayTable/types.tsx
+++ b/static/app/views/replays/replayTable/types.tsx
@@ -2,8 +2,10 @@ export enum ReplayColumn {
ACTIVITY = 'activity',
BROWSER = 'browser',
COUNT_DEAD_CLICKS = 'countDeadClicks',
+ COUNT_DEAD_CLICKS_NO_HEADER = 'countDeadClicksNoHeader',
COUNT_ERRORS = 'countErrors',
COUNT_RAGE_CLICKS = 'countRageClicks',
+ COUNT_RAGE_CLICKS_NO_HEADER = 'countRageClicksNoHeader',
DURATION = 'duration',
MOST_ERRONEOUS_REPLAYS = 'mostErroneousReplays',
MOST_RAGE_CLICKS = 'mostRageClicks',
|
c8f06d7336b357fdbfcfcf1a6f5211728ada2f84
|
2020-10-02 14:23:02
|
Matej Minar
|
feat(ui): Add unhandled label to issue stream + detail (#20882)
| false
|
Add unhandled label to issue stream + detail (#20882)
|
feat
|
diff --git a/src/sentry/static/sentry/app/components/eventOrGroupHeader.tsx b/src/sentry/static/sentry/app/components/eventOrGroupHeader.tsx
index 18759495c5e4f4..71aa5cbd0bb8f9 100644
--- a/src/sentry/static/sentry/app/components/eventOrGroupHeader.tsx
+++ b/src/sentry/static/sentry/app/components/eventOrGroupHeader.tsx
@@ -11,6 +11,9 @@ import EventOrGroupTitle from 'app/components/eventOrGroupTitle';
import Tooltip from 'app/components/tooltip';
import {getMessage, getLocation} from 'app/utils/events';
import GlobalSelectionLink from 'app/components/globalSelectionLink';
+import UnhandledTag, {
+ TagAndMessageWrapper,
+} from 'app/views/organizationGroupDetails/unhandledTag';
type DefaultProps = {
includeLink: boolean;
@@ -102,12 +105,18 @@ class EventOrGroupHeader extends React.Component<Props> {
const {className, size, data} = this.props;
const location = getLocation(data);
const message = getMessage(data);
+ const {isUnhandled} = data as Group;
return (
<div className={className} data-test-id="event-issue-header">
<Title size={size}>{this.getTitle()}</Title>
{location && <Location size={size}>{location}</Location>}
- {message && <Message size={size}>{message}</Message>}
+ {(message || isUnhandled) && (
+ <StyledTagAndMessageWrapper size={size}>
+ {isUnhandled && <UnhandledTag />}
+ {message && <Message>{message}</Message>}
+ </StyledTagAndMessageWrapper>
+ )}
</div>
);
}
@@ -162,9 +171,12 @@ function Location(props) {
);
}
+const StyledTagAndMessageWrapper = styled(TagAndMessageWrapper)`
+ ${getMargin};
+`;
+
const Message = styled('div')`
${truncateStyles};
- ${getMargin};
font-size: ${p => p.theme.fontSizeMedium};
`;
diff --git a/src/sentry/static/sentry/app/components/events/eventMessage.tsx b/src/sentry/static/sentry/app/components/events/eventMessage.tsx
index ca4ff76fd82553..94aaebf3d772dc 100644
--- a/src/sentry/static/sentry/app/components/events/eventMessage.tsx
+++ b/src/sentry/static/sentry/app/components/events/eventMessage.tsx
@@ -49,10 +49,7 @@ const StyledEventMessage = styled(EventMessage)`
align-items: center;
position: relative;
line-height: 1.2;
-
- @media (max-width: ${p => p.theme.breakpoints[0]}) {
- margin-bottom: ${space(2)};
- }
+ overflow: hidden;
`;
const StyledErrorLevel = styled(ErrorLevel)`
diff --git a/src/sentry/static/sentry/app/types/index.tsx b/src/sentry/static/sentry/app/types/index.tsx
index 209efa690cc4bc..933ef0c3690234 100644
--- a/src/sentry/static/sentry/app/types/index.tsx
+++ b/src/sentry/static/sentry/app/types/index.tsx
@@ -672,6 +672,7 @@ export type Group = {
firstSeen: string;
hasSeen: boolean;
isBookmarked: boolean;
+ isUnhandled: boolean;
isPublic: boolean;
isSubscribed: boolean;
lastRelease: any; // TODO(ts)
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/header.jsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/header.jsx
index 6afeee6969e92a..f5b5ab61aed3ca 100644
--- a/src/sentry/static/sentry/app/views/organizationGroupDetails/header.jsx
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/header.jsx
@@ -24,6 +24,7 @@ import space from 'app/styles/space';
import withApi from 'app/utils/withApi';
import GroupActions from './actions';
+import UnhandledTag, {TagAndMessageWrapper} from './unhandledTag';
const TAB = {
DETAILS: 'details',
@@ -114,33 +115,35 @@ class GroupHeader extends React.Component {
<h3>
<EventOrGroupTitle hasGuideAnchor data={group} />
</h3>
-
- <EventMessage
- message={message}
- level={group.level}
- annotations={
- <React.Fragment>
- {group.logger && (
- <EventAnnotationWithSpace>
- <Link
- to={{
- pathname: `/organizations/${orgId}/issues/`,
- query: {query: 'logger:' + group.logger},
- }}
- >
- {group.logger}
- </Link>
- </EventAnnotationWithSpace>
- )}
- {group.annotations.map((annotation, i) => (
- <EventAnnotationWithSpace
- key={i}
- dangerouslySetInnerHTML={{__html: annotation}}
- />
- ))}
- </React.Fragment>
- }
- />
+ <StyledTagAndMessageWrapper>
+ {group.isUnhandled && <UnhandledTag />}
+ <EventMessage
+ message={message}
+ level={group.level}
+ annotations={
+ <React.Fragment>
+ {group.logger && (
+ <EventAnnotationWithSpace>
+ <Link
+ to={{
+ pathname: `/organizations/${orgId}/issues/`,
+ query: {query: 'logger:' + group.logger},
+ }}
+ >
+ {group.logger}
+ </Link>
+ </EventAnnotationWithSpace>
+ )}
+ {group.annotations.map((annotation, i) => (
+ <EventAnnotationWithSpace
+ key={i}
+ dangerouslySetInnerHTML={{__html: annotation}}
+ />
+ ))}
+ </React.Fragment>
+ }
+ />
+ </StyledTagAndMessageWrapper>
</div>
<div className="col-sm-5 stats">
@@ -256,6 +259,12 @@ class GroupHeader extends React.Component {
}
}
+const StyledTagAndMessageWrapper = styled(TagAndMessageWrapper)`
+ @media (max-width: ${p => p.theme.breakpoints[0]}) {
+ margin-bottom: ${space(2)};
+ }
+`;
+
const StyledProjectBadge = styled(ProjectBadge)`
flex-shrink: 0;
`;
diff --git a/src/sentry/static/sentry/app/views/organizationGroupDetails/unhandledTag.tsx b/src/sentry/static/sentry/app/views/organizationGroupDetails/unhandledTag.tsx
new file mode 100644
index 00000000000000..64e5f27b16b4c1
--- /dev/null
+++ b/src/sentry/static/sentry/app/views/organizationGroupDetails/unhandledTag.tsx
@@ -0,0 +1,45 @@
+import React from 'react';
+import styled from '@emotion/styled';
+
+import {t} from 'app/locale';
+import space from 'app/styles/space';
+import Tag from 'app/components/tag';
+import Feature from 'app/components/acl/feature';
+import Tooltip from 'app/components/tooltip';
+import {IconSubtract} from 'app/icons';
+
+const TagWrapper = styled('div')`
+ margin-right: ${space(1)};
+`;
+
+const TagAndMessageWrapper = styled('div')`
+ display: flex;
+ align-items: center;
+`;
+
+// TODO(matej): remove "unhandled-issue-flag" feature flag once testing is over (otherwise this won't ever be rendered in a shared event)
+const UnhandledTag = styled((props: React.ComponentProps<typeof Tag>) => (
+ <Feature features={['unhandled-issue-flag']}>
+ <TagWrapper>
+ <Tooltip title={t('An unhandled error was detected in this Issue.')}>
+ <Tag
+ priority="error"
+ icon={<IconSubtract size="xs" color="red300" isCircled />}
+ {...props}
+ >
+ {t('Unhandled')}
+ </Tag>
+ </Tooltip>
+ </TagWrapper>
+ </Feature>
+))`
+ /* TODO(matej): There is going to be a major Tag component refactor which should make Tags look something like this - then we can remove these one-off styles */
+ background-color: #ffecf0;
+ color: ${p => p.theme.gray700};
+ text-transform: none;
+ padding: 0 ${space(1)};
+ height: 21px;
+`;
+
+export default UnhandledTag;
+export {TagAndMessageWrapper};
diff --git a/src/sentry/static/sentry/app/views/sharedGroupDetails/sharedGroupHeader.tsx b/src/sentry/static/sentry/app/views/sharedGroupDetails/sharedGroupHeader.tsx
index e9858a06c8aa65..09c3a672f9aa15 100644
--- a/src/sentry/static/sentry/app/views/sharedGroupDetails/sharedGroupHeader.tsx
+++ b/src/sentry/static/sentry/app/views/sharedGroupDetails/sharedGroupHeader.tsx
@@ -6,6 +6,10 @@ import space from 'app/styles/space';
import {Group} from 'app/types';
import overflowEllipsis from 'app/styles/overflowEllipsis';
+import UnhandledTag, {
+ TagAndMessageWrapper,
+} from '../organizationGroupDetails/unhandledTag';
+
type Props = {
group: Group;
};
@@ -14,7 +18,10 @@ const SharedGroupHeader = ({group}: Props) => (
<Wrapper>
<Details>
<Title>{group.title}</Title>
- <EventMessage message={group.culprit} />
+ <TagAndMessageWrapper>
+ {group.isUnhandled && <UnhandledTag />}
+ <EventMessage message={group.culprit} />
+ </TagAndMessageWrapper>
</Details>
</Wrapper>
);
|
856c373fc8cf595c3d4276cb29607750357b2d3d
|
2023-07-04 19:20:45
|
Jonas
|
ref(userfeedback): convert test to tsx (#52038)
| false
|
convert test to tsx (#52038)
|
ref
|
diff --git a/static/app/views/asyncView.tsx b/static/app/views/asyncView.tsx
index bdd6dcb6dea551..7e89ea41d94d5c 100644
--- a/static/app/views/asyncView.tsx
+++ b/static/app/views/asyncView.tsx
@@ -1,8 +1,8 @@
import AsyncComponent from 'sentry/components/asyncComponent';
import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
-type AsyncViewState = AsyncComponent['state'];
-type AsyncViewProps = AsyncComponent['props'];
+export type AsyncViewState = AsyncComponent['state'];
+export type AsyncViewProps = AsyncComponent['props'];
export default class AsyncView<
P extends AsyncViewProps = AsyncViewProps,
diff --git a/static/app/views/userFeedback/index.spec.jsx b/static/app/views/userFeedback/index.spec.tsx
similarity index 88%
rename from static/app/views/userFeedback/index.spec.jsx
rename to static/app/views/userFeedback/index.spec.tsx
index 0f270cf9238a9a..fdeb2f19bb9677 100644
--- a/static/app/views/userFeedback/index.spec.jsx
+++ b/static/app/views/userFeedback/index.spec.tsx
@@ -12,6 +12,14 @@ describe('UserFeedback', function () {
const project = TestStubs.Project({isMember: true});
+ const routeProps = {
+ routes: router.routes,
+ route: {},
+ router,
+ location: router.location,
+ routeParams: router.params,
+ };
+
beforeEach(function () {
ProjectsStore.loadInitialData([project]);
@@ -34,10 +42,10 @@ describe('UserFeedback', function () {
it('renders', function () {
const params = {
organization: TestStubs.Organization(),
- location: {query: {}, search: ''},
params: {
orgId: organization.slug,
},
+ ...routeProps,
};
MockApiClient.addMockResponse({
@@ -56,10 +64,10 @@ describe('UserFeedback', function () {
const params = {
organization: TestStubs.Organization(),
- location: {query: {}, search: ''},
params: {
orgId: organization.slug,
},
+ ...routeProps,
};
render(<UserFeedback {...params} />, {context: routerContext});
@@ -78,10 +86,10 @@ describe('UserFeedback', function () {
organization: TestStubs.Organization({
projects: [TestStubs.Project({isMember: true})],
}),
- location: {query: {}, search: ''},
params: {
orgId: organization.slug,
},
+ ...routeProps,
};
render(<UserFeedback {...params} />, {context: routerContext});
@@ -95,10 +103,16 @@ describe('UserFeedback', function () {
});
const params = {
+ ...routeProps,
organization: TestStubs.Organization({
projects: [TestStubs.Project({isMember: true})],
}),
- location: {pathname: 'sentry', query: {project: '112'}, search: ''},
+ location: {
+ ...routeProps.location,
+ pathname: 'sentry',
+ query: {project: '112'},
+ search: '',
+ },
params: {
orgId: organization.slug,
},
@@ -113,11 +127,10 @@ describe('UserFeedback', function () {
organization: TestStubs.Organization({
projects: [TestStubs.Project({isMember: true})],
}),
- location: router.location,
params: {
orgId: organization.slug,
},
- router,
+ ...routeProps,
};
render(<UserFeedback {...params} />, {context: routerContext});
@@ -144,10 +157,16 @@ describe('UserFeedback', function () {
});
const params = {
+ ...routeProps,
organization: TestStubs.Organization({
projects: [TestStubs.Project({isMember: true})],
}),
- location: {pathname: 'sentry', query: {project: ['112', '113']}, search: ''},
+ location: {
+ ...routeProps.location,
+ pathname: 'sentry',
+ query: {project: ['112', '113']},
+ search: '',
+ },
params: {
orgId: organization.slug,
},
diff --git a/static/app/views/userFeedback/index.tsx b/static/app/views/userFeedback/index.tsx
index 49ed2715480d51..9441170c9c7c7f 100644
--- a/static/app/views/userFeedback/index.tsx
+++ b/static/app/views/userFeedback/index.tsx
@@ -21,18 +21,18 @@ import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
import {Organization, UserReport} from 'sentry/types';
import withOrganization from 'sentry/utils/withOrganization';
-import AsyncView from 'sentry/views/asyncView';
+import AsyncView, {AsyncViewState} from 'sentry/views/asyncView';
import {UserFeedbackEmpty} from './userFeedbackEmpty';
import {getQuery} from './utils';
-type State = AsyncView['state'] & {
+interface State extends AsyncViewState {
reportList: UserReport[];
-};
+}
-type Props = RouteComponentProps<{}, {}> & {
+interface Props extends RouteComponentProps<{}, {}> {
organization: Organization;
-};
+}
class OrganizationUserFeedback extends AsyncView<Props, State> {
getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
|
515f724e61d47134f4112b12cd295e2a99c68e8c
|
2022-06-14 03:22:08
|
Aniket Das
|
chore(django-3.2): Update django-rest-framework to 3.12.4 (#35520)
| false
|
Update django-rest-framework to 3.12.4 (#35520)
|
chore
|
diff --git a/requirements-base.txt b/requirements-base.txt
index 0cd40bdeef28ce..a8b8e14f674700 100644
--- a/requirements-base.txt
+++ b/requirements-base.txt
@@ -12,7 +12,7 @@ django-crispy-forms==1.14.0
django-picklefield==2.1.0
django-pg-zero-downtime-migrations==0.10
Django==2.2.28
-djangorestframework==3.11.2
+djangorestframework==3.12.4
drf-spectacular==0.22.1
email-reply-parser==0.5.12
google-api-core==1.25.1
|
9f235d9d444d21fe38031ab51307fbd8e06153a5
|
2022-03-23 03:52:02
|
Evan Purkhiser
|
chore(lint): Fix linting of docs-ui code (#32851)
| false
|
Fix linting of docs-ui code (#32851)
|
chore
|
diff --git a/docs-ui/components/code.tsx b/docs-ui/components/code.tsx
index cee779af90fa00..5f6bf689d76964 100644
--- a/docs-ui/components/code.tsx
+++ b/docs-ui/components/code.tsx
@@ -17,7 +17,6 @@ import space from 'sentry/styles/space';
import {Theme} from 'sentry/utils/theme';
type Props = {
- theme?: Theme;
/**
* Main code content gets passed as the children prop
*/
@@ -38,6 +37,7 @@ type Props = {
* the label prop is set to 'hello'
*/
label?: string;
+ theme?: Theme;
};
const Code = ({children, className, label}: Props) => {
diff --git a/docs-ui/components/doDont.tsx b/docs-ui/components/doDont.tsx
index cb2cf15dfc7cc7..a36512d5262187 100644
--- a/docs-ui/components/doDont.tsx
+++ b/docs-ui/components/doDont.tsx
@@ -6,8 +6,8 @@ import space from 'sentry/styles/space';
type BoxContent = {
text: string;
img?: {
- src: string;
alt: string;
+ src: string;
};
};
type BoxProps = BoxContent & {
diff --git a/docs-ui/components/docsLinks.tsx b/docs-ui/components/docsLinks.tsx
index a88e2e8b821ec2..4b61872b100489 100644
--- a/docs-ui/components/docsLinks.tsx
+++ b/docs-ui/components/docsLinks.tsx
@@ -7,12 +7,6 @@ import space from 'sentry/styles/space';
import {Theme} from 'sentry/utils/theme';
type Link = {
- img?: {
- src: string;
- alt: string;
- };
- title: string;
- desc?: string;
/**
* props to pass to LinkTo:
*
@@ -26,6 +20,12 @@ type Link = {
*/
kind: string;
story: string;
+ title: string;
+ desc?: string;
+ img?: {
+ alt: string;
+ src: string;
+ };
};
type LinkProps = Link;
diff --git a/docs-ui/components/sample.tsx b/docs-ui/components/sample.tsx
index d8103184348c0e..e129b7a5190ec4 100644
--- a/docs-ui/components/sample.tsx
+++ b/docs-ui/components/sample.tsx
@@ -10,6 +10,10 @@ type ThemeName = 'dark' | 'light';
type Props = {
children?: React.ReactChild;
+ /**
+ * Remove the outer border and padding
+ */
+ noBorder?: boolean;
/**
* Show the theme switcher, which allows for
* switching the local theme context between
@@ -17,10 +21,6 @@ type Props = {
* components in both modes.
*/
showThemeSwitcher?: boolean;
- /**
- * Remove the outer border and padding
- */
- noBorder?: boolean;
};
/**
@@ -73,7 +73,7 @@ const Wrap = styled('div')`
position: relative;
`;
-const InnerWrap = styled('div')<{noBorder: boolean; addTopMargin: boolean}>`
+const InnerWrap = styled('div')<{addTopMargin: boolean; noBorder: boolean}>`
position: relative;
border-radius: ${p => p.theme.borderRadius};
margin: ${space(2)} 0;
diff --git a/docs-ui/stories/assets/icons/sample.tsx b/docs-ui/stories/assets/icons/sample.tsx
index 7c61a5e685ee11..5259f85e2013fb 100644
--- a/docs-ui/stories/assets/icons/sample.tsx
+++ b/docs-ui/stories/assets/icons/sample.tsx
@@ -2,12 +2,12 @@ import * as Icons from 'app/icons';
import {Aliases, Color, IconSize} from 'app/utils/theme';
type Props = {
+ color: Color | Aliases;
name: string;
size: IconSize;
- color: Color | Aliases;
+ direction?: 'left' | 'right' | 'up' | 'down';
isCircled?: boolean;
isSolid?: boolean;
- direction?: 'left' | 'right' | 'up' | 'down';
type?: 'line' | 'circle' | 'bar';
};
diff --git a/docs-ui/stories/core/colors/colorSwatch.tsx b/docs-ui/stories/core/colors/colorSwatch.tsx
index d0c465ab9ef54f..bcde9d627fe4af 100644
--- a/docs-ui/stories/core/colors/colorSwatch.tsx
+++ b/docs-ui/stories/core/colors/colorSwatch.tsx
@@ -6,8 +6,8 @@ import space from 'sentry/styles/space';
import {darkColors, lightColors} from 'sentry/utils/theme';
type Props = {
- theme: 'light' | 'dark';
colors: Array<keyof typeof lightColors>;
+ theme: 'light' | 'dark';
};
const ColorSwatch = ({colors, theme}: Props) => {
@@ -55,7 +55,7 @@ const ColorWrap = styled('div')<{value: string}>`
padding: ${space(2)} ${space(2)};
`;
-const Label = styled('p')<{color: boolean}>`
+const Label = styled('p')<{color: string}>`
margin-bottom: 0;
white-space: nowrap;
&& {
diff --git a/docs-ui/stories/core/colors/tables.tsx b/docs-ui/stories/core/colors/tables.tsx
index a45bd1f1b0ee9c..b0d0121d38d4f6 100644
--- a/docs-ui/stories/core/colors/tables.tsx
+++ b/docs-ui/stories/core/colors/tables.tsx
@@ -9,8 +9,8 @@ import {lightColors} from 'sentry/utils/theme';
import ColorSwatch from './colorSwatch';
type ColorGroup = {
- id: string;
colors: Array<keyof typeof lightColors>;
+ id: string;
};
const Wrap = styled('div')`
diff --git a/docs-ui/stories/core/typography/tables.tsx b/docs-ui/stories/core/typography/tables.tsx
index 4af3ed0a296b64..8b8e05b117f6cd 100644
--- a/docs-ui/stories/core/typography/tables.tsx
+++ b/docs-ui/stories/core/typography/tables.tsx
@@ -10,26 +10,26 @@ import {
type TypeStyle = {
fontFamily?: string;
- fontWeight?: number;
fontSize?: string;
- lineHeight?: number;
+ fontWeight?: number;
letterSpacing?: string;
+ lineHeight?: number;
};
type TypeDefinition = {
name: string;
+ style: TypeStyle;
/**
* HTML tag (h1, h2, p) used to render type element
*/
tag: keyof JSX.IntrinsicElements;
- style: TypeStyle;
};
type Column = {
- colName: string;
- key?: keyof TypeStyle | keyof TypeDefinition;
align: 'left' | 'right' | 'center';
+ colName: string;
tabularFigures: boolean;
+ key?: keyof TypeStyle | keyof TypeDefinition;
};
const sampleColumn: Column = {
diff --git a/package.json b/package.json
index fb4e11dcd784c1..b5902bc9e763c9 100644
--- a/package.json
+++ b/package.json
@@ -211,7 +211,7 @@
"test-ci": "yarn test --ci --coverage --runInBand",
"test-debug": "node --inspect-brk scripts/test.js --runInBand",
"test-staged": "yarn test --findRelatedTests $(git diff --name-only --cached)",
- "lint": "yarn eslint tests/js static/app --ext .js,.jsx,.ts,.tsx",
+ "lint": "yarn eslint static/app tests/js docs-ui/ --ext .js,.jsx,.ts,.tsx",
"lint:css": "yarn stylelint 'static/app/**/*.[jt]sx'",
"dev": "(yarn check --verify-tree || yarn install --check-files) && sentry devserver",
"dev-ui": "SENTRY_UI_DEV_ONLY=1 SENTRY_WEBPACK_PROXY_PORT=7999 yarn webpack serve",
|
8ccb1241f4acfc6af8c13d3736855e4ea56a4071
|
2025-01-14 21:10:52
|
Sebastian Zivota
|
feat(symx): Add a log message (#83381)
| false
|
Add a log message (#83381)
|
feat
|
diff --git a/src/sentry/lang/native/processing.py b/src/sentry/lang/native/processing.py
index 448e02c0ced262..775272f1c3ef05 100644
--- a/src/sentry/lang/native/processing.py
+++ b/src/sentry/lang/native/processing.py
@@ -540,6 +540,10 @@ def emit_apple_symbol_stats(apple_symbol_stats, data):
if in_random_rollout("symbolicate.symx-logging-rate") and os_name and os_version:
os_description = os_name + str(os_version)
if os_description in options.get("symbolicate.symx-os-description-list"):
+ logger.info(
+ "Failed to find symbols using symx",
+ extra={"id": data.get("event_id"), "modules": old},
+ )
with sentry_sdk.isolation_scope() as scope:
scope.set_context(
"Event Info", {"id": data.get("event_id"), "modules": str(old)}
|
3193e36e804c6d558613a43cd57e37dc1cf6120a
|
2024-08-02 22:20:47
|
Tony Xiao
|
feat(profiling): Do not require transactions for landing page flamegraph (#75366)
| false
|
Do not require transactions for landing page flamegraph (#75366)
|
feat
|
diff --git a/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts
index dedbc0c3376295..ecf6334026d1e6 100644
--- a/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts
+++ b/static/app/utils/profiling/hooks/useAggregateFlamegraphQuery.ts
@@ -8,28 +8,56 @@ import type RequestError from 'sentry/utils/requestError/requestError';
import useOrganization from 'sentry/utils/useOrganization';
import usePageFilters from 'sentry/utils/usePageFilters';
-export interface AggregateFlamegraphQueryParameters {
- query: string;
+interface BaseAggregateFlamegraphQueryParameters {
datetime?: PageFilters['datetime'];
enabled?: boolean;
environments?: PageFilters['environments'];
- fingerprint?: string;
projects?: PageFilters['projects'];
}
+interface FunctionsAggregateFlamegraphQueryParameters
+ extends BaseAggregateFlamegraphQueryParameters {
+ query: string;
+ dataSource?: 'functions';
+ fingerprint?: string;
+}
+
+interface TransactionsAggregateFlamegraphQueryParameters
+ extends BaseAggregateFlamegraphQueryParameters {
+ query: string;
+ dataSource?: 'transactions';
+}
+
+interface ProfilesAggregateFlamegraphQueryParameters
+ extends BaseAggregateFlamegraphQueryParameters {
+ dataSource: 'profiles';
+}
+
+export type AggregateFlamegraphQueryParameters =
+ | FunctionsAggregateFlamegraphQueryParameters
+ | TransactionsAggregateFlamegraphQueryParameters
+ | ProfilesAggregateFlamegraphQueryParameters;
+
export type UseAggregateFlamegraphQueryResult = UseApiQueryResult<
Profiling.Schema,
RequestError
>;
-export function useAggregateFlamegraphQuery({
- datetime,
- enabled,
- environments,
- projects,
- query,
- fingerprint,
-}: AggregateFlamegraphQueryParameters): UseAggregateFlamegraphQueryResult {
+export function useAggregateFlamegraphQuery(
+ props: AggregateFlamegraphQueryParameters
+): UseAggregateFlamegraphQueryResult {
+ const {dataSource, datetime, enabled, environments, projects} = props;
+
+ let fingerprint: string | undefined = undefined;
+ let query: string | undefined = undefined;
+
+ if (isDataSourceFunctions(props)) {
+ fingerprint = props.fingerprint;
+ query = props.query;
+ } else if (isDataSourceTransactions(props)) {
+ query = props.query;
+ }
+
const organization = useOrganization();
const {selection} = usePageFilters();
@@ -39,13 +67,14 @@ export function useAggregateFlamegraphQuery({
project: projects ?? selection.projects,
environment: environments ?? selection.environments,
...normalizeDateTimeParams(datetime ?? selection.datetime),
+ dataSource,
fingerprint,
query,
},
};
return params;
- }, [datetime, environments, projects, fingerprint, query, selection]);
+ }, [dataSource, datetime, environments, projects, fingerprint, query, selection]);
return useApiQuery<Profiling.Schema>(
[`/organizations/${organization.slug}/profiling/flamegraph/`, endpointOptions],
@@ -56,3 +85,21 @@ export function useAggregateFlamegraphQuery({
}
);
}
+
+function isDataSourceProfiles(
+ props: AggregateFlamegraphQueryParameters
+): props is ProfilesAggregateFlamegraphQueryParameters {
+ return 'dataSource' in props && props.dataSource === 'profiles';
+}
+
+function isDataSourceFunctions(
+ props: AggregateFlamegraphQueryParameters
+): props is FunctionsAggregateFlamegraphQueryParameters {
+ return 'fingerprint' in props;
+}
+
+function isDataSourceTransactions(
+ props: AggregateFlamegraphQueryParameters
+): props is TransactionsAggregateFlamegraphQueryParameters {
+ return !isDataSourceProfiles(props) && isDataSourceFunctions(props);
+}
diff --git a/static/app/views/profiling/landingAggregateFlamegraph.tsx b/static/app/views/profiling/landingAggregateFlamegraph.tsx
index c552c45ce0312c..84da25ec21d981 100644
--- a/static/app/views/profiling/landingAggregateFlamegraph.tsx
+++ b/static/app/views/profiling/landingAggregateFlamegraph.tsx
@@ -133,7 +133,7 @@ export function LandingAggregateFlamegraph(): React.ReactNode {
const location = useLocation();
const {data, isLoading, isError} = useAggregateFlamegraphQuery({
- query: '',
+ dataSource: 'profiles',
});
const [visualization, setVisualization] = useLocalStorageState<
|
45f47330ad07ad7956d87cf44d29205469f69877
|
2021-09-24 22:57:46
|
Shruthi
|
chore(analytics): Add some analytics around chart unfurls (#28807)
| false
|
Add some analytics around chart unfurls (#28807)
|
chore
|
diff --git a/src/sentry/integrations/slack/analytics.py b/src/sentry/integrations/slack/analytics.py
index 239efc6adc848a..ea9b0eefaef1c7 100644
--- a/src/sentry/integrations/slack/analytics.py
+++ b/src/sentry/integrations/slack/analytics.py
@@ -28,6 +28,27 @@ class SlackIntegrationNotificationSent(analytics.Event): # type: ignore
)
+class IntegrationSlackChartUnfurl(analytics.Event): # type: ignore
+ type = "integrations.slack.chart_unfurl"
+
+ attributes = (
+ analytics.Attribute("user_id", required=False),
+ analytics.Attribute("organization_id"),
+ analytics.Attribute("unfurls_count", type=int),
+ )
+
+
+class IntegrationSlackLinkIdentity(analytics.Event): # type: ignore
+ type = "integrations.slack.chart_unfurl_action"
+
+ attributes = (
+ analytics.Attribute("organization_id"),
+ analytics.Attribute("action"),
+ )
+
+
analytics.register(SlackIntegrationAssign)
analytics.register(SlackIntegrationNotificationSent)
analytics.register(SlackIntegrationStatus)
+analytics.register(IntegrationSlackChartUnfurl)
+analytics.register(IntegrationSlackLinkIdentity)
diff --git a/src/sentry/integrations/slack/endpoints/action.py b/src/sentry/integrations/slack/endpoints/action.py
index d4f66d71c2b324..db2656c7ef9479 100644
--- a/src/sentry/integrations/slack/endpoints/action.py
+++ b/src/sentry/integrations/slack/endpoints/action.py
@@ -194,9 +194,15 @@ def post(self, request: Request) -> Response:
channel_id = slack_request.channel_id
user_id = slack_request.user_id
+ integration = slack_request.integration
response_url = data.get("response_url")
if action_option in ["link", "ignore"]:
+ analytics.record(
+ "integrations.slack.chart_unfurl_action",
+ organization_id=integration.organizations.all()[0].id,
+ action=action_option,
+ )
payload = {"delete_original": "true"}
try:
post(response_url, json=payload)
@@ -209,8 +215,6 @@ def post(self, request: Request) -> Response:
logging_data["channel_id"] = channel_id
logging_data["slack_user_id"] = user_id
logging_data["response_url"] = response_url
-
- integration = slack_request.integration
logging_data["integration_id"] = integration.id
# Determine the issue group action is being taken on
diff --git a/src/sentry/integrations/slack/endpoints/event.py b/src/sentry/integrations/slack/endpoints/event.py
index a0398a6b113dae..1a691733e1c40e 100644
--- a/src/sentry/integrations/slack/endpoints/event.py
+++ b/src/sentry/integrations/slack/endpoints/event.py
@@ -4,7 +4,7 @@
from rest_framework.request import Request
from rest_framework.response import Response
-from sentry import features
+from sentry import analytics, features
from sentry.integrations.slack.client import SlackClient
from sentry.integrations.slack.message_builder.base.block import BlockSlackMessageBuilder
from sentry.integrations.slack.message_builder.event import SlackEventMessageBuilder
@@ -172,6 +172,11 @@ def on_link_shared(
actor=request.user,
)
):
+ analytics.record(
+ "integrations.slack.chart_unfurl",
+ organization_id=integration.organizations.all()[0].id,
+ unfurls_count=0,
+ )
self.prompt_link(data, slack_request, integration)
return self.respond()
diff --git a/src/sentry/integrations/slack/unfurl/discover.py b/src/sentry/integrations/slack/unfurl/discover.py
index e521c67377a71b..737cc0ba312948 100644
--- a/src/sentry/integrations/slack/unfurl/discover.py
+++ b/src/sentry/integrations/slack/unfurl/discover.py
@@ -5,7 +5,7 @@
from django.http.request import HttpRequest, QueryDict
-from sentry import features
+from sentry import analytics, features
from sentry.api import client
from sentry.charts import generate_chart
from sentry.charts.types import ChartType
@@ -132,6 +132,13 @@ def unfurl_discover(
chart_url=url,
)
+ analytics.record(
+ "integrations.slack.chart_unfurl",
+ organization_id=integration.organizations.all()[0].id,
+ user_id=user.id if user else None,
+ unfurls_count=len(unfurls),
+ )
+
return unfurls
|
047ba7b088b06166804839e7db086adc87b0762d
|
2022-11-09 01:34:57
|
Vu Luong
|
fix(tabs): Prevent focus on <a /> tags inside tab links (#41135)
| false
|
Prevent focus on <a /> tags inside tab links (#41135)
|
fix
|
diff --git a/static/app/components/tabs/tab.tsx b/static/app/components/tabs/tab.tsx
index f26e81ad020a08..723e55273c3f27 100644
--- a/static/app/components/tabs/tab.tsx
+++ b/static/app/components/tabs/tab.tsx
@@ -61,6 +61,7 @@ function BaseTab(
onMouseDown={handleLinkClick}
onPointerDown={handleLinkClick}
orientation={orientation}
+ tabIndex={-1}
>
{children}
</TabLink>
|
84d3f6c04913571f2c965b050c89eee791918cc3
|
2021-06-11 00:57:18
|
Dora
|
fix(chart footer): column to flow (#26527)
| false
|
column to flow (#26527)
|
fix
|
diff --git a/static/app/components/charts/styles.tsx b/static/app/components/charts/styles.tsx
index 766eb955ad37a2..4c42e208119855 100644
--- a/static/app/components/charts/styles.tsx
+++ b/static/app/components/charts/styles.tsx
@@ -32,8 +32,11 @@ export const SectionValue = styled('span')`
export const InlineContainer = styled('div')`
display: grid;
align-items: center;
- grid-template-columns: max-content auto;
- grid-gap: ${space(1)};
+
+ @media (min-width: ${p => p.theme.breakpoints[0]}) {
+ grid-auto-flow: column;
+ grid-column-gap: ${space(1)};
+ }
`;
export const ChartControls = styled('div')`
@@ -43,6 +46,7 @@ export const ChartControls = styled('div')`
@media (min-width: ${p => p.theme.breakpoints[0]}) {
display: flex;
justify-content: space-between;
+ flex-wrap: wrap;
}
`;
|
8f769d5920c4c87b33f7dab01598878656389855
|
2024-12-20 23:17:06
|
Colleen O'Rourke
|
feat(ACI): Remove DataConditions condition field (#82403)
| false
|
Remove DataConditions condition field (#82403)
|
feat
|
diff --git a/migrations_lockfile.txt b/migrations_lockfile.txt
index e9fb7d22ebadef..0ec7da63fda40d 100644
--- a/migrations_lockfile.txt
+++ b/migrations_lockfile.txt
@@ -23,4 +23,4 @@ tempest: 0001_create_tempest_credentials_model
uptime: 0021_drop_region_table_col
-workflow_engine: 0018_rm_data_condition_condition
+workflow_engine: 0019_drop_dataconditions_condition
diff --git a/src/sentry/workflow_engine/migrations/0019_drop_dataconditions_condition.py b/src/sentry/workflow_engine/migrations/0019_drop_dataconditions_condition.py
new file mode 100644
index 00000000000000..9c96936d1ec154
--- /dev/null
+++ b/src/sentry/workflow_engine/migrations/0019_drop_dataconditions_condition.py
@@ -0,0 +1,33 @@
+# Generated by Django 5.1.4 on 2024-12-19 19:56
+
+from sentry.new_migrations.migrations import CheckedMigration
+from sentry.new_migrations.monkey.fields import SafeRemoveField
+from sentry.new_migrations.monkey.state import DeletionAction
+
+
+class Migration(CheckedMigration):
+ # This flag is used to mark that a migration shouldn't be automatically run in production.
+ # This should only be used for operations where it's safe to run the migration after your
+ # code has deployed. So this should not be used for most operations that alter the schema
+ # of a table.
+ # Here are some things that make sense to mark as post deployment:
+ # - Large data migrations. Typically we want these to be run manually so that they can be
+ # monitored and not block the deploy for a long period of time while they run.
+ # - Adding indexes to large tables. Since this can take a long time, we'd generally prefer to
+ # run this outside deployments so that we don't block them. Note that while adding an index
+ # is a schema change, it's completely safe to run the operation after the code has deployed.
+ # Once deployed, run these manually via: https://develop.sentry.dev/database-migrations/#migration-deployment
+
+ is_post_deployment = False
+
+ dependencies = [
+ ("workflow_engine", "0018_rm_data_condition_condition"),
+ ]
+
+ operations = [
+ SafeRemoveField(
+ model_name="datacondition",
+ name="condition",
+ deletion_action=DeletionAction.DELETE,
+ ),
+ ]
|
7903be01b309b4dc2884bc555c107c3c133aa68b
|
2023-02-06 13:07:50
|
Joris Bayer
|
fix(txnames): Run clusterer at fixed time every hour (#44096)
| false
|
Run clusterer at fixed time every hour (#44096)
|
fix
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index eed35f5bcaebaf..a9500791c4d168 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -827,7 +827,7 @@ def SOCIAL_AUTH_DEFAULT_USERNAME():
},
"transaction-name-clusterer": {
"task": "sentry.ingest.transaction_clusterer.tasks.spawn_clusterers",
- "schedule": timedelta(hours=1),
+ "schedule": crontab(minute=17),
"options": {"expires": 3600},
},
"hybrid-cloud-repair-mappings": {
|
98c829ce35d9fb2552855a687707284460119d11
|
2025-02-06 03:25:13
|
Malachi Willey
|
ref(nav): Render primary nav items directly (#84637)
| false
|
Render primary nav items directly (#84637)
|
ref
|
diff --git a/static/app/components/nav/primary.tsx b/static/app/components/nav/primary.tsx
index 2239deedd3c406..b1000e0d6f0979 100644
--- a/static/app/components/nav/primary.tsx
+++ b/static/app/components/nav/primary.tsx
@@ -7,11 +7,7 @@ import {DropdownMenu, type MenuItemProps} from 'sentry/components/dropdownMenu';
import InteractionStateLayer from 'sentry/components/interactionStateLayer';
import Link from 'sentry/components/links/link';
import {linkStyles} from 'sentry/components/links/styles';
-import {
- isLinkActive,
- makeLinkPropsFromTo,
- type NavSidebarItem,
-} from 'sentry/components/nav/utils';
+import {isLinkActive, makeLinkPropsFromTo} from 'sentry/components/nav/utils';
import {
IconDashboard,
IconGraph,
@@ -29,13 +25,8 @@ import normalizeUrl from 'sentry/utils/url/normalizeUrl';
import {useLocation} from 'sentry/utils/useLocation';
import useOrganization from 'sentry/utils/useOrganization';
-interface SidebarItemProps {
- item: NavSidebarItem;
- children?: React.ReactNode;
- onClick?: MouseEventHandler<HTMLElement>;
-}
-
interface SidebarItemLinkProps {
+ analyticsKey: string;
to: string;
activeTo?: string;
children?: React.ReactNode;
@@ -43,9 +34,9 @@ interface SidebarItemLinkProps {
}
interface SidebarItemDropdownProps {
+ analyticsKey: string;
items: MenuItemProps[];
children?: React.ReactNode;
- onClick?: MouseEventHandler<HTMLElement>;
}
function SidebarBody({children}: {children: React.ReactNode}) {
@@ -60,83 +51,60 @@ function SidebarFooter({children}: {children: React.ReactNode}) {
);
}
-function SidebarItem({item}: SidebarItemProps) {
+function SidebarMenu({items, children, analyticsKey}: SidebarItemDropdownProps) {
const organization = useOrganization();
-
const recordAnalytics = useCallback(
- () =>
- trackAnalytics('growth.clicked_sidebar', {item: item.analyticsKey, organization}),
- [organization, item.analyticsKey]
+ () => trackAnalytics('growth.clicked_sidebar', {item: analyticsKey, organization}),
+ [organization, analyticsKey]
);
- if (item.to) {
- return (
- <SidebarItemWrapper>
- <SidebarLink
- to={item.to}
- activeTo={item.activeTo}
- key={item.label}
- onClick={recordAnalytics}
- >
- {item.icon}
- <span>{item.label}</span>
- </SidebarLink>
- </SidebarItemWrapper>
- );
- }
-
- if (item.dropdown) {
- return (
- <SidebarItemWrapper>
- <SidebarMenu items={item.dropdown} key={item.label} onClick={recordAnalytics}>
- {item.icon}
- <span>{item.label}</span>
- </SidebarMenu>
- </SidebarItemWrapper>
- );
- }
-
- return null;
-}
-
-function SidebarMenu({items, children, onClick}: SidebarItemDropdownProps) {
return (
- <DropdownMenu
- position="right-end"
- trigger={(props, isOpen) => {
- return (
- <NavButton
- {...props}
- onClick={event => {
- onClick?.(event);
- props.onClick?.(event);
- }}
- >
- <InteractionStateLayer hasSelectedBackground={isOpen} />
- {children}
- </NavButton>
- );
- }}
- items={items}
- />
+ <SidebarItemWrapper>
+ <DropdownMenu
+ position="right-end"
+ trigger={(props, isOpen) => {
+ return (
+ <NavButton
+ {...props}
+ onClick={event => {
+ recordAnalytics();
+ props.onClick?.(event);
+ }}
+ >
+ <InteractionStateLayer hasSelectedBackground={isOpen} />
+ {children}
+ </NavButton>
+ );
+ }}
+ items={items}
+ />
+ </SidebarItemWrapper>
);
}
-function SidebarLink({children, to, activeTo = to, onClick}: SidebarItemLinkProps) {
+function SidebarLink({children, to, activeTo = to, analyticsKey}: SidebarItemLinkProps) {
+ const organization = useOrganization();
const location = useLocation();
const isActive = isLinkActive(normalizeUrl(activeTo, location), location.pathname);
const linkProps = makeLinkPropsFromTo(to);
+ const recordAnalytics = useCallback(
+ () => trackAnalytics('growth.clicked_sidebar', {item: analyticsKey, organization}),
+ [organization, analyticsKey]
+ );
+
return (
- <NavLink
- {...linkProps}
- onClick={onClick}
- aria-selected={isActive}
- aria-current={isActive ? 'page' : undefined}
- >
- <InteractionStateLayer hasSelectedBackground={isActive} />
- {children}
- </NavLink>
+ <SidebarItemWrapper>
+ <NavLink
+ {...linkProps}
+ onClick={recordAnalytics}
+ aria-selected={isActive}
+ aria-current={isActive ? 'page' : undefined}
+ >
+ <InteractionStateLayer hasSelectedBackground={isActive} />
+ {children}
+ </NavLink>
+ </SidebarItemWrapper>
);
}
@@ -147,96 +115,86 @@ export function PrimaryNavigationItems() {
return (
<Fragment>
<SidebarBody>
- <SidebarItem
- item={{
- label: t('Issues'),
- icon: <IconIssues />,
- analyticsKey: 'issues',
- to: `/${prefix}/issues/`,
- }}
- />
- <SidebarItem
- item={{
- label: t('Explore'),
- icon: <IconSearch />,
- analyticsKey: 'explore',
- to: `/${prefix}/explore/traces/`,
- }}
- />
+ <SidebarLink to={`/${prefix}/issues/`} analyticsKey="issues">
+ <IconIssues />
+ <span>{t('Issues')}</span>
+ </SidebarLink>
+
+ <SidebarLink to={`/${prefix}/explore/traces/`} analyticsKey="explore">
+ <IconSearch />
+ <span>{t('Explore')}</span>
+ </SidebarLink>
+
<Feature
features={['discover', 'discover-query', 'dashboards-basic', 'dashboards-edit']}
hookName="feature-disabled:dashboards-sidebar-item"
requireAll={false}
>
- <SidebarItem
- item={{
- label: t('Boards'),
- icon: <IconDashboard />,
- analyticsKey: 'customizable-dashboards',
- to: `/${prefix}/dashboards/`,
- }}
- />
+ <SidebarLink
+ to={`/${prefix}/dashboards/`}
+ analyticsKey="customizable-dashboards"
+ >
+ <IconDashboard />
+ <span>{t('Boards')}</span>
+ </SidebarLink>
</Feature>
+
<Feature features={['performance-view']}>
- <SidebarItem
- item={{
- label: t('Insights'),
- icon: <IconGraph />,
- analyticsKey: 'insights-domains',
- to: `/${prefix}/insights/frontend/`,
- }}
- />
+ <SidebarLink
+ to={`/${prefix}/insights/frontend/`}
+ analyticsKey="insights-domains"
+ >
+ <IconGraph />
+ <span>{t('Insights')}</span>
+ </SidebarLink>
</Feature>
</SidebarBody>
+
<SidebarFooter>
- <SidebarItem
- item={{
- label: t('Help'),
- icon: <IconQuestion />,
- analyticsKey: 'help',
- dropdown: [
- {
- key: 'search',
- label: t('Search Support, Docs and More'),
- onAction() {
- openHelpSearchModal({organization});
- },
- },
- {
- key: 'help',
- label: t('Visit Help Center'),
- to: 'https://sentry.zendesk.com/hc/en-us',
+ <SidebarMenu
+ items={[
+ {
+ key: 'search',
+ label: t('Search Support, Docs and More'),
+ onAction() {
+ openHelpSearchModal({organization});
},
- {
- key: 'discord',
- label: t('Join our Discord'),
- to: 'https://discord.com/invite/sentry',
- },
- {
- key: 'support',
- label: t('Contact Support'),
- to: `mailto:${ConfigStore.get('supportEmail')}`,
- },
- ],
- }}
- />
- <SidebarItem
- item={{
- label: t('Stats'),
- icon: <IconStats />,
- analyticsKey: 'stats',
- to: `/${prefix}/stats/`,
- }}
- />
- <SidebarItem
- item={{
- label: t('Settings'),
- icon: <IconSettings />,
- analyticsKey: 'settings',
- to: `/${prefix}/settings/${organization.slug}/`,
- activeTo: `/${prefix}/settings/`,
- }}
- />
+ },
+ {
+ key: 'help',
+ label: t('Visit Help Center'),
+ to: 'https://sentry.zendesk.com/hc/en-us',
+ },
+ {
+ key: 'discord',
+ label: t('Join our Discord'),
+ to: 'https://discord.com/invite/sentry',
+ },
+ {
+ key: 'support',
+ label: t('Contact Support'),
+ to: `mailto:${ConfigStore.get('supportEmail')}`,
+ },
+ ]}
+ analyticsKey="help"
+ >
+ <IconQuestion />
+ <span>{t('Help')}</span>
+ </SidebarMenu>
+
+ <SidebarLink to={`/${prefix}/stats/`} analyticsKey="stats">
+ <IconStats />
+ <span>{t('Stats')}</span>
+ </SidebarLink>
+
+ <SidebarLink
+ to={`/${prefix}/settings/`}
+ activeTo={`/${prefix}/settings/`}
+ analyticsKey="settings"
+ >
+ <IconSettings />
+ <span>{t('Settings')}</span>
+ </SidebarLink>
</SidebarFooter>
</Fragment>
);
diff --git a/static/app/components/nav/utils.tsx b/static/app/components/nav/utils.tsx
index 9b08b40676bd28..c46fe8fcdf1e2a 100644
--- a/static/app/components/nav/utils.tsx
+++ b/static/app/components/nav/utils.tsx
@@ -1,79 +1,9 @@
import type {To} from '@remix-run/router';
import type {LocationDescriptor} from 'history';
-import type {FeatureProps} from 'sentry/components/acl/feature';
-import type {MenuItemProps} from 'sentry/components/dropdownMenu';
import {SIDEBAR_NAVIGATION_SOURCE} from 'sentry/components/sidebar/utils';
import normalizeUrl from 'sentry/utils/url/normalizeUrl';
-/**
- * NavItem is the base class for both SidebarItem and SubmenuItem
- */
-interface NavItem {
- /**
- * User-facing item label, surfaced in the UI. Should be translated!
- */
- label: string;
- /**
- * Optionally, props which should be passed to a wrapping `<Feature>` guard
- */
- feature?: FeatureProps;
-}
-
-/**
- * NavItems are displayed in either `main` and `footer` sections
- */
-export interface NavItemLayout<Item extends NavSidebarItem | NavSubmenuItem> {
- main: Item[];
- footer?: Item[];
-}
-
-/**
- * SidebarItem is a top-level NavItem which is always displayed in the app sidebar
- */
-export interface NavSidebarItem extends NavItem {
- /**
- * A unique identifier string, used as a key for analytics
- */
- analyticsKey: string;
- /**
- * The icon to render in the sidebar
- */
- icon: React.ReactElement;
- /**
- * Defines the path that should be considered active for this item.
- * Defaults to the `to` prop.
- */
- activeTo?: string;
- /**
- * dropdown menu to display when this SidebarItem is clicked
- */
- dropdown?: MenuItemProps[];
- /**
- * Optionally, the submenu items to display when this SidebarItem is active
- */
- submenu?: NavSubmenuItem[] | NavItemLayout<NavSubmenuItem>;
- /**
- * The pathname (including `search` params) to navigate to when the item is clicked.
- * Defaults to the `to` property of the first `SubmenuItem` if excluded.
- */
- to?: string;
-}
-
-/**
- * SubmenuItem is a secondary NavItem which is only displayed when its parent SidebarItem is active
- */
-export interface NavSubmenuItem extends NavItem {
- /**
- * The pathname (including `search` params) to navigate to when the item is clicked.
- */
- to: string;
-}
-
-export type NavConfig = NavItemLayout<NavSidebarItem>;
-
-export type NavigationItemStatus = 'inactive' | 'active' | 'active-parent';
-
export function isLinkActive(
to: To,
pathname: string,
@@ -112,7 +42,3 @@ export function makeLinkPropsFromTo(to: string): {
state: {source: SIDEBAR_NAVIGATION_SOURCE},
};
}
-
-export function isNonEmptyArray(item: unknown): item is any[] {
- return Array.isArray(item) && item.length > 0;
-}
|
e94aa8916bff3ec78843a9cbb83471c2b1f814b7
|
2019-03-06 20:16:10
|
Mark Story
|
fix: Fix prop-type warning (#12295)
| false
|
Fix prop-type warning (#12295)
|
fix
|
diff --git a/src/sentry/static/sentry/app/components/fileChange.jsx b/src/sentry/static/sentry/app/components/fileChange.jsx
index 03557f0b0f46ce..2addb1b0f32cc3 100644
--- a/src/sentry/static/sentry/app/components/fileChange.jsx
+++ b/src/sentry/static/sentry/app/components/fileChange.jsx
@@ -23,7 +23,7 @@ class FileChange extends React.PureComponent {
<li className="list-group-item list-group-item-sm release-file-change">
<div className="row row-flex row-center-vertically">
<div className="col-sm-10 truncate file-name">
- <InlineSvg src="icon-file" className="icon-file-generic" size={15} />
+ <InlineSvg src="icon-file" className="icon-file-generic" size="15" />
{filename}
</div>
<div className="col-sm-2 avatar-grid align-right">
|
7f76eaa0a8f3e6b282bfa901d5642ef8f9909010
|
2023-01-25 03:08:55
|
Scott Cooper
|
fix(issues): Group undefined in assignee selector (#43652)
| false
|
Group undefined in assignee selector (#43652)
|
fix
|
diff --git a/static/app/components/assigneeSelector.tsx b/static/app/components/assigneeSelector.tsx
index 37bcca152b0200..392576fb4ebb73 100644
--- a/static/app/components/assigneeSelector.tsx
+++ b/static/app/components/assigneeSelector.tsx
@@ -16,7 +16,7 @@ import {t, tct, tn} from 'sentry/locale';
import GroupStore from 'sentry/stores/groupStore';
import {useLegacyStore} from 'sentry/stores/useLegacyStore';
import space from 'sentry/styles/space';
-import type {Actor, Group, SuggestedOwnerReason} from 'sentry/types';
+import type {Actor, SuggestedOwnerReason} from 'sentry/types';
import useOrganization from 'sentry/utils/useOrganization';
interface AssigneeSelectorProps
@@ -124,19 +124,19 @@ function AssigneeAvatar({
function AssigneeSelector({noDropdown, ...props}: AssigneeSelectorProps) {
const organization = useOrganization();
const groups = useLegacyStore(GroupStore);
- const group = groups.find(item => item.id === props.id) as Group;
+ const group = groups.find(item => item.id === props.id);
return (
<AssigneeWrapper>
<AssigneeSelectorDropdown
organization={organization}
- assignedTo={group.assignedTo}
+ assignedTo={group?.assignedTo}
{...props}
>
{({loading, isOpen, getActorProps, suggestedAssignees}) => {
const avatarElement = (
<AssigneeAvatar
- assignedTo={group.assignedTo}
+ assignedTo={group?.assignedTo}
suggestedActors={suggestedAssignees}
/>
);
|
e5035c845000036a444e2a6ff9d036ca8a1f438f
|
2025-03-19 01:21:03
|
Michael Sun
|
ref(shared-views): Remove position usage in groupsearchview serializer (#87297)
| false
|
Remove position usage in groupsearchview serializer (#87297)
|
ref
|
diff --git a/src/sentry/api/serializers/models/groupsearchview.py b/src/sentry/api/serializers/models/groupsearchview.py
index 6f0fe87bcd004e..4bb2e6b333b26d 100644
--- a/src/sentry/api/serializers/models/groupsearchview.py
+++ b/src/sentry/api/serializers/models/groupsearchview.py
@@ -13,7 +13,6 @@ class GroupSearchViewSerializerResponse(TypedDict):
name: str
query: str
querySort: SORT_LITERALS
- position: int
projects: list[int]
isAllProjects: bool
environments: list[str]
@@ -23,6 +22,10 @@ class GroupSearchViewSerializerResponse(TypedDict):
dateUpdated: str
+class GroupSearchViewStarredSerializerResponse(GroupSearchViewSerializerResponse):
+ position: int
+
+
@register(GroupSearchView)
class GroupSearchViewSerializer(Serializer):
def __init__(self, *args, **kwargs):
@@ -67,7 +70,6 @@ def serialize(self, obj, attrs, user, **kwargs) -> GroupSearchViewSerializerResp
"name": obj.name,
"query": obj.query,
"querySort": obj.query_sort,
- "position": obj.position,
"projects": projects,
"isAllProjects": is_all_projects,
"environments": obj.environments,
@@ -86,7 +88,7 @@ def __init__(self, *args, **kwargs):
self.organization = kwargs.pop("organization", None)
super().__init__(*args, **kwargs)
- def serialize(self, obj, attrs, user, **kwargs) -> GroupSearchViewSerializerResponse:
+ def serialize(self, obj, attrs, user, **kwargs) -> GroupSearchViewStarredSerializerResponse:
serialized_view: GroupSearchViewSerializerResponse = serialize(
obj.group_search_view,
user,
diff --git a/src/sentry/issues/endpoints/organization_group_search_views.py b/src/sentry/issues/endpoints/organization_group_search_views.py
index ef3b71a2c3fc5a..16814a2aad9f3d 100644
--- a/src/sentry/issues/endpoints/organization_group_search_views.py
+++ b/src/sentry/issues/endpoints/organization_group_search_views.py
@@ -13,15 +13,13 @@
from sentry.api.helpers.group_index.validators import ValidationError
from sentry.api.paginator import SequencePaginator
from sentry.api.serializers import serialize
-from sentry.api.serializers.models.groupsearchview import (
- GroupSearchViewSerializer,
- GroupSearchViewStarredSerializer,
-)
+from sentry.api.serializers.models.groupsearchview import GroupSearchViewStarredSerializer
from sentry.api.serializers.rest_framework.groupsearchview import (
GroupSearchViewValidator,
GroupSearchViewValidatorResponse,
)
from sentry.models.groupsearchview import DEFAULT_TIME_FILTER, GroupSearchView
+from sentry.models.groupsearchviewlastvisited import GroupSearchViewLastVisited
from sentry.models.groupsearchviewstarred import GroupSearchViewStarred
from sentry.models.organization import Organization
from sentry.models.project import Project
@@ -157,7 +155,9 @@ def put(self, request: Request, organization: Organization) -> Response:
try:
with transaction.atomic(using=router.db_for_write(GroupSearchView)):
- bulk_update_views(organization, request.user.id, validated_data["views"])
+ new_view_state = bulk_update_views(
+ organization, request.user.id, validated_data["views"]
+ )
except IntegrityError as e:
if (
len(e.args) > 0
@@ -171,13 +171,38 @@ def put(self, request: Request, organization: Organization) -> Response:
)
return Response(status=status.HTTP_500_INTERNAL_SERVER_ERROR)
- query = GroupSearchView.objects.filter(organization=organization, user_id=request.user.id)
+ last_visited_views = GroupSearchViewLastVisited.objects.filter(
+ organization=organization,
+ user_id=request.user.id,
+ group_search_view_id__in=[view.id for view in new_view_state],
+ )
+ last_visited_map = {lv.group_search_view_id: lv for lv in last_visited_views}
return self.paginate(
request=request,
- queryset=query,
- order_by="position",
- on_results=lambda x: serialize(x, request.user, serializer=GroupSearchViewSerializer()),
+ paginator=SequencePaginator(
+ [
+ (
+ idx,
+ {
+ "id": str(view.id),
+ "name": view.name,
+ "query": view.query,
+ "querySort": view.query_sort,
+ "projects": list(view.projects.values_list("id", flat=True)),
+ "isAllProjects": view.is_all_projects,
+ "environments": view.environments,
+ "timeFilters": view.time_filters,
+ "dateCreated": view.date_added,
+ "dateUpdated": view.date_updated,
+ "lastVisited": last_visited_map.get(view.id, None),
+ "position": idx,
+ },
+ )
+ for idx, view in enumerate(new_view_state)
+ ]
+ ),
+ on_results=lambda results: serialize(results, request.user),
)
@@ -198,16 +223,18 @@ def validate_projects(
def bulk_update_views(
org: Organization, user_id: int, views: list[GroupSearchViewValidatorResponse]
-) -> None:
+) -> list[GroupSearchView]:
existing_view_ids = [view["id"] for view in views if "id" in view]
_delete_missing_views(org, user_id, view_ids_to_keep=existing_view_ids)
-
+ created_views = []
for idx, view in enumerate(views):
if "id" not in view:
- _create_view(org, user_id, view, position=idx)
+ created_views.append(_create_view(org, user_id, view, position=idx))
else:
- _update_existing_view(org, user_id, view, position=idx)
+ created_views.append(_update_existing_view(org, user_id, view, position=idx))
+
+ return created_views
def pick_default_project(org: Organization, user: User | AnonymousUser) -> int | None:
@@ -230,7 +257,7 @@ def _delete_missing_views(org: Organization, user_id: int, view_ids_to_keep: lis
def _update_existing_view(
org: Organization, user_id: int, view: GroupSearchViewValidatorResponse, position: int
-) -> None:
+) -> GroupSearchView:
try:
gsv = GroupSearchView.objects.get(id=view["id"], user_id=user_id)
gsv.name = view["name"]
@@ -255,17 +282,18 @@ def _update_existing_view(
group_search_view=gsv,
defaults={"position": position},
)
+ return gsv
except GroupSearchView.DoesNotExist:
# It is possible – though unlikely under normal circumstances – for a view to come in that
# doesn't exist anymore. If, for example, the user has the issue stream open in separate
# windows, deletes a view in one window, then updates it in the other before refreshing.
# In this case, we decide to recreate the tab instead of leaving it deleted.
- _create_view(org, user_id, view, position)
+ return _create_view(org, user_id, view, position)
def _create_view(
org: Organization, user_id: int, view: GroupSearchViewValidatorResponse, position: int
-) -> None:
+) -> GroupSearchView:
gsv = GroupSearchView.objects.create(
organization=org,
user_id=user_id,
@@ -286,3 +314,4 @@ def _create_view(
group_search_view=gsv,
position=position,
)
+ return gsv
diff --git a/tests/sentry/issues/endpoints/test_organization_group_search_views.py b/tests/sentry/issues/endpoints/test_organization_group_search_views.py
index cab6b0bea414b9..9532d8926e3501 100644
--- a/tests/sentry/issues/endpoints/test_organization_group_search_views.py
+++ b/tests/sentry/issues/endpoints/test_organization_group_search_views.py
@@ -2,7 +2,6 @@
from django.utils import timezone
from rest_framework.exceptions import ErrorDetail
-from sentry.api.serializers.base import serialize
from sentry.api.serializers.rest_framework.groupsearchview import GroupSearchViewValidatorResponse
from sentry.issues.endpoints.organization_group_search_views import DEFAULT_VIEWS
from sentry.models.groupsearchview import GroupSearchView
@@ -136,7 +135,12 @@ def test_get_user_one_custom_views(self) -> None:
self.login_as(user=self.user)
response = self.get_success_response(self.organization.slug)
- assert response.data == serialize(objs["user_one_views"])
+ assert response.data[0]["id"] == str(objs["user_one_views"][0].id)
+ assert response.data[0]["position"] == 0
+ assert response.data[1]["id"] == str(objs["user_one_views"][1].id)
+ assert response.data[1]["position"] == 1
+ assert response.data[2]["id"] == str(objs["user_one_views"][2].id)
+ assert response.data[2]["position"] == 2
@with_feature({"organizations:issue-stream-custom-views": True})
@with_feature({"organizations:global-views": True})
@@ -169,7 +173,10 @@ def test_get_user_two_custom_views(self) -> None:
self.login_as(user=self.user_2)
response = self.get_success_response(self.organization.slug)
- assert response.data == serialize(objs["user_two_views"])
+ assert response.data[0]["id"] == str(objs["user_two_views"][0].id)
+ assert response.data[0]["position"] == 0
+ assert response.data[1]["id"] == str(objs["user_two_views"][1].id)
+ assert response.data[1]["position"] == 1
@with_feature({"organizations:issue-stream-custom-views": True})
@with_feature({"organizations:global-views": True})
|
7a60aae6ec5efe8a54beccac089e94bc344fea48
|
2024-03-23 02:29:36
|
Evan Purkhiser
|
feat(crons): Add logging to mark_ok resolve (#67537)
| false
|
Add logging to mark_ok resolve (#67537)
|
feat
|
diff --git a/src/sentry/monitors/logic/mark_ok.py b/src/sentry/monitors/logic/mark_ok.py
index 2985937f745625..36e69c8addf89e 100644
--- a/src/sentry/monitors/logic/mark_ok.py
+++ b/src/sentry/monitors/logic/mark_ok.py
@@ -1,7 +1,10 @@
+import logging
from datetime import datetime
from sentry.monitors.models import CheckInStatus, MonitorCheckIn, MonitorEnvironment, MonitorStatus
+logger = logging.getLogger(__name__)
+
def mark_ok(checkin: MonitorCheckIn, ts: datetime):
monitor_env = checkin.monitor_environment
@@ -48,6 +51,14 @@ def mark_ok(checkin: MonitorCheckIn, ts: datetime):
resolving_checkin=checkin,
resolving_timestamp=checkin.date_added,
)
+ logger.info(
+ "monitors.logic.mark_ok.resolving_incident",
+ extra={
+ "monitor_env_id": monitor_env.id,
+ "incident_id": incident.id,
+ "grouphash": incident.grouphash,
+ },
+ )
MonitorEnvironment.objects.filter(id=monitor_env.id).exclude(last_checkin__gt=ts).update(
**params
|
86fdeacbe92805f0dd5e9bf3cf84ca58ab3f9f4f
|
2020-08-29 03:01:47
|
k-fish
|
fix(trends): Add current trend function field to request (#20492)
| false
|
Add current trend function field to request (#20492)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/performance/trends/utils.tsx b/src/sentry/static/sentry/app/views/performance/trends/utils.tsx
index c8cce15c10f614..7b5d00ad9de20b 100644
--- a/src/sentry/static/sentry/app/views/performance/trends/utils.tsx
+++ b/src/sentry/static/sentry/app/views/performance/trends/utils.tsx
@@ -128,9 +128,13 @@ export function modifyTrendView(
trendsType: TrendChangeType
) {
const trendFunction = getCurrentTrendFunction(location);
- const fields = ['transaction', 'project', 'count()'].map(field => ({
- field,
- })) as Field[];
+
+ const trendFunctionFields = TRENDS_FUNCTIONS.map(({field}) => field);
+ const fields = [...trendFunctionFields, 'transaction', 'project', 'count()'].map(
+ field => ({
+ field,
+ })
+ ) as Field[];
const trendSort = {
field: `percentage_${trendFunction.alias}_2_${trendFunction.alias}_1`,
diff --git a/tests/js/spec/views/performance/trends.spec.jsx b/tests/js/spec/views/performance/trends.spec.jsx
index 4d7d4afa28ab13..25499b392bd26e 100644
--- a/tests/js/spec/views/performance/trends.spec.jsx
+++ b/tests/js/spec/views/performance/trends.spec.jsx
@@ -267,6 +267,13 @@ describe('Performance > Trends', function() {
const aliasedFieldDivide = getTrendAliasedFieldPercentage(trendFunction.alias);
const aliasedQueryDivide = getTrendAliasedQueryPercentage(trendFunction.alias);
+ const defaultFields = ['transaction', 'project', 'count()'];
+ const trendFunctionFields = TRENDS_FUNCTIONS.map(({field}) => field);
+
+ const field = [...trendFunctionFields, ...defaultFields];
+
+ expect(field).toHaveLength(6);
+
// Improved trends call
expect(trendsMock).toHaveBeenNthCalledWith(
1,
@@ -277,6 +284,7 @@ describe('Performance > Trends', function() {
sort: aliasedFieldDivide,
query: expect.stringContaining(aliasedQueryDivide + ':<1'),
interval: '1h',
+ field,
}),
})
);
@@ -291,6 +299,7 @@ describe('Performance > Trends', function() {
sort: '-' + aliasedFieldDivide,
query: expect.stringContaining(aliasedQueryDivide + ':>1'),
interval: '1h',
+ field,
}),
})
);
|
8aae75842cfe26f1aed3eb63a20b20397c5a008e
|
2023-03-21 03:35:46
|
Evan Purkhiser
|
ref(monitors): Remove ApiKeyAuthentication from monitor ingest (#46017)
| false
|
Remove ApiKeyAuthentication from monitor ingest (#46017)
|
ref
|
diff --git a/src/sentry/monitors/endpoints/base.py b/src/sentry/monitors/endpoints/base.py
index e847f3c58c99d3..d5160f6995c7ad 100644
--- a/src/sentry/monitors/endpoints/base.py
+++ b/src/sentry/monitors/endpoints/base.py
@@ -4,7 +4,7 @@
from rest_framework.request import Request
-from sentry.api.authentication import ApiKeyAuthentication, DSNAuthentication, TokenAuthentication
+from sentry.api.authentication import DSNAuthentication, TokenAuthentication
from sentry.api.base import Endpoint
from sentry.api.bases.organization import OrganizationPermission
from sentry.api.bases.project import ProjectPermission
@@ -120,7 +120,7 @@ class MonitorIngestEndpoint(Endpoint):
checkin ingestion in the very near future.
"""
- authentication_classes = (DSNAuthentication, TokenAuthentication, ApiKeyAuthentication)
+ authentication_classes = (DSNAuthentication, TokenAuthentication)
permission_classes = (ProjectMonitorPermission,)
allow_auto_create_monitors = False
|
195c00649047fccb5c070003e4c3fa7beb2f64df
|
2023-08-14 22:09:22
|
anthony sottile
|
ref: fix more typing issues (#54604)
| false
|
fix more typing issues (#54604)
|
ref
|
diff --git a/pyproject.toml b/pyproject.toml
index e64470dace0d59..ccc5718b3eff6d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -513,7 +513,6 @@ module = [
"sentry.integrations.slack.message_builder.notifications.issues",
"sentry.integrations.slack.notifications",
"sentry.integrations.slack.unfurl.discover",
- "sentry.integrations.slack.unfurl.issues",
"sentry.integrations.slack.utils.channel",
"sentry.integrations.slack.utils.users",
"sentry.integrations.slack.views.link_identity",
@@ -899,71 +898,16 @@ module = [
"tests.sentry.eventstore.test_base",
"tests.sentry.grouping.test_result",
"tests.sentry.identity.test_oauth2",
- "tests.sentry.incidents.action_handlers",
- "tests.sentry.incidents.action_handlers.test_sentry_app",
- "tests.sentry.incidents.action_handlers.test_slack",
"tests.sentry.incidents.endpoints.test_organization_alert_rule_details",
"tests.sentry.incidents.endpoints.test_organization_alert_rule_index",
"tests.sentry.incidents.endpoints.test_organization_incident_details",
"tests.sentry.incidents.endpoints.test_organization_incident_subscription_index",
"tests.sentry.incidents.endpoints.test_project_alert_rule_index",
- "tests.sentry.incidents.endpoints.test_serializers",
- "tests.sentry.incidents.test_charts",
"tests.sentry.incidents.test_logic",
- "tests.sentry.incidents.test_models",
- "tests.sentry.incidents.test_subscription_processor",
- "tests.sentry.incidents.test_tasks",
- "tests.sentry.ingest.billing_metrics_consumer.test_billing_metrics_consumer_kafka",
- "tests.sentry.ingest.ingest_consumer.test_ingest_consumer_kafka",
"tests.sentry.ingest.test_slicing",
- "tests.sentry.ingest.test_span_desc_clusterer",
- "tests.sentry.ingest.test_transaction_clusterer",
- "tests.sentry.ingest.test_transaction_rule_validator",
- "tests.sentry.integrations.bitbucket.test_installed",
- "tests.sentry.integrations.bitbucket.test_issues",
"tests.sentry.integrations.github.test_client",
- "tests.sentry.integrations.github.test_integration",
- "tests.sentry.integrations.github.test_issues",
- "tests.sentry.integrations.gitlab.test_client",
- "tests.sentry.integrations.gitlab.test_integration",
- "tests.sentry.integrations.jira.test_client",
- "tests.sentry.integrations.jira.test_integration",
- "tests.sentry.integrations.jira.test_webhooks",
- "tests.sentry.integrations.jira_server",
- "tests.sentry.integrations.jira_server.test_integration",
- "tests.sentry.integrations.jira_server.test_webhooks",
- "tests.sentry.integrations.msteams.notifications.test_deploy",
- "tests.sentry.integrations.msteams.notifications.test_escalating",
- "tests.sentry.integrations.msteams.notifications.test_note",
- "tests.sentry.integrations.msteams.notifications.test_regression",
- "tests.sentry.integrations.msteams.notifications.test_resolved",
- "tests.sentry.integrations.msteams.notifications.test_unassigned",
- "tests.sentry.integrations.msteams.test_action_state_change",
- "tests.sentry.integrations.msteams.test_client",
"tests.sentry.integrations.msteams.test_message_builder",
- "tests.sentry.integrations.msteams.test_notifications",
- "tests.sentry.integrations.msteams.test_notify_action",
- "tests.sentry.integrations.msteams.test_webhook",
- "tests.sentry.integrations.pagerduty.test_client",
- "tests.sentry.integrations.pagerduty.test_notify_action",
- "tests.sentry.integrations.slack.notifications.test_assigned",
- "tests.sentry.integrations.slack.notifications.test_deploy",
- "tests.sentry.integrations.slack.notifications.test_escalating",
- "tests.sentry.integrations.slack.notifications.test_issue_alert",
- "tests.sentry.integrations.slack.notifications.test_new_processing_issues",
- "tests.sentry.integrations.slack.notifications.test_note",
- "tests.sentry.integrations.slack.notifications.test_regression",
- "tests.sentry.integrations.slack.notifications.test_resolved",
- "tests.sentry.integrations.slack.notifications.test_resolved_in_release",
- "tests.sentry.integrations.slack.notifications.test_unassigned",
- "tests.sentry.integrations.slack.test_client",
- "tests.sentry.integrations.slack.test_integration",
- "tests.sentry.integrations.slack.test_message_builder",
- "tests.sentry.integrations.slack.test_notifications",
- "tests.sentry.integrations.slack.test_notify_action",
"tests.sentry.integrations.slack.test_requests",
- "tests.sentry.integrations.slack.test_unfurl",
- "tests.sentry.integrations.slack.test_uninstall",
"tests.sentry.issues.test_utils",
"tests.sentry.lang.javascript.test_processor",
"tests.sentry.models.test_organizationmember",
diff --git a/src/sentry/incidents/models.py b/src/sentry/incidents/models.py
index e65fc11c824f58..72d93885d0a003 100644
--- a/src/sentry/incidents/models.py
+++ b/src/sentry/incidents/models.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from collections import namedtuple
from enum import Enum
@@ -254,7 +256,7 @@ class IncidentActivity(Model):
incident = FlexibleForeignKey("sentry.Incident")
user_id = HybridCloudForeignKey(settings.AUTH_USER_MODEL, on_delete="CASCADE", null=True)
- type = models.IntegerField()
+ type: models.Field[int | IncidentActivityType, int] = models.IntegerField()
value = models.TextField(null=True)
previous_value = models.TextField(null=True)
comment = models.TextField(null=True)
diff --git a/src/sentry/incidents/subscription_processor.py b/src/sentry/incidents/subscription_processor.py
index 705892bb71a1eb..708639522c12ba 100644
--- a/src/sentry/incidents/subscription_processor.py
+++ b/src/sentry/incidents/subscription_processor.py
@@ -777,7 +777,7 @@ def build_trigger_stat_keys(
def build_alert_rule_trigger_stat_key(
- alert_rule_id: int, project_id: int, trigger_id: str, stat_key: str
+ alert_rule_id: int, project_id: int, trigger_id: int, stat_key: str
) -> str:
key_base = ALERT_RULE_BASE_KEY % (alert_rule_id, project_id)
return ALERT_RULE_BASE_TRIGGER_STAT_KEY % (key_base, trigger_id, stat_key)
@@ -830,8 +830,8 @@ def update_alert_rule_stats(
alert_rule: AlertRule,
subscription: QuerySubscription,
last_update: datetime,
- alert_counts: Dict[str, int],
- resolve_counts: Dict[str, int],
+ alert_counts: Dict[int, int],
+ resolve_counts: Dict[int, int],
) -> None:
"""
Updates stats about the alert rule, subscription and triggers if they've changed.
diff --git a/src/sentry/ingest/billing_metrics_consumer.py b/src/sentry/ingest/billing_metrics_consumer.py
index f1575ca0e25a91..e509ddf3b84872 100644
--- a/src/sentry/ingest/billing_metrics_consumer.py
+++ b/src/sentry/ingest/billing_metrics_consumer.py
@@ -10,6 +10,7 @@
from arroyo.processing.strategies import ProcessingStrategy, ProcessingStrategyFactory
from arroyo.types import Commit, Message, Partition
from django.conf import settings
+from typing_extensions import NotRequired
from sentry.constants import DataCategory
from sentry.sentry_metrics.indexer.strings import SHARED_TAG_STRINGS, TRANSACTION_METRICS_NAMES
@@ -79,6 +80,8 @@ class MetricsBucket(TypedDict):
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]):
diff --git a/src/sentry/integrations/github/client.py b/src/sentry/integrations/github/client.py
index 112e2059b67342..1d7aa136ecdd7b 100644
--- a/src/sentry/integrations/github/client.py
+++ b/src/sentry/integrations/github/client.py
@@ -18,6 +18,7 @@
from sentry.models import Integration, Repository
from sentry.services.hybrid_cloud.integration import RpcIntegration
from sentry.services.hybrid_cloud.util import control_silo_function
+from sentry.shared_integrations.client.base import BaseApiResponseX
from sentry.shared_integrations.client.proxy import IntegrationProxyClient
from sentry.shared_integrations.exceptions.base import ApiError
from sentry.types.integrations import EXTERNAL_PROVIDERS, ExternalProviders
@@ -583,11 +584,8 @@ def get_user(self, gh_username: str) -> JSONData:
"""
return self.get(f"/users/{gh_username}")
- def check_file(self, repo: Repository, path: str, version: str) -> str | None:
- file: str = self.head_cached(
- path=f"/repos/{repo.name}/contents/{path}", params={"ref": version}
- )
- return file
+ def check_file(self, repo: Repository, path: str, version: str) -> BaseApiResponseX:
+ return self.head_cached(path=f"/repos/{repo.name}/contents/{path}", params={"ref": version})
def get_file(self, repo: Repository, path: str, ref: str) -> str:
"""Get the contents of a file
diff --git a/src/sentry/integrations/opsgenie/utils.py b/src/sentry/integrations/opsgenie/utils.py
index 18337afed9d33c..0c2960309d817b 100644
--- a/src/sentry/integrations/opsgenie/utils.py
+++ b/src/sentry/integrations/opsgenie/utils.py
@@ -1,5 +1,7 @@
+from __future__ import annotations
+
import logging
-from typing import Optional
+from typing import Any, Optional
from sentry.constants import ObjectStatus
from sentry.incidents.models import AlertRuleTriggerAction, Incident, IncidentStatus
@@ -12,7 +14,9 @@
from .client import OpsgenieClient
-def build_incident_attachment(incident: Incident, new_status: IncidentStatus, metric_value=None):
+def build_incident_attachment(
+ incident: Incident, new_status: IncidentStatus, metric_value: int | None = None
+) -> dict[str, Any]:
data = incident_attachment_info(incident, new_status, metric_value)
alert_key = f"incident_{incident.organization_id}_{incident.identifier}"
if new_status == IncidentStatus.CLOSED:
diff --git a/src/sentry/integrations/pagerduty/utils.py b/src/sentry/integrations/pagerduty/utils.py
index 6778ce8a8f2dae..740c9026a50c81 100644
--- a/src/sentry/integrations/pagerduty/utils.py
+++ b/src/sentry/integrations/pagerduty/utils.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import logging
+from typing import Any
from django.http import Http404
@@ -20,8 +21,8 @@
def build_incident_attachment(
- incident, integration_key, new_status: IncidentStatus, metric_value=None
-):
+ incident, integration_key, new_status: IncidentStatus, metric_value: int | None = None
+) -> dict[str, Any]:
data = incident_attachment_info(incident, new_status, metric_value)
severity = "info"
if new_status == IncidentStatus.CRITICAL:
diff --git a/src/sentry/integrations/slack/unfurl/__init__.py b/src/sentry/integrations/slack/unfurl/__init__.py
index a41a4a2e1010d6..dcd32cbaba7063 100644
--- a/src/sentry/integrations/slack/unfurl/__init__.py
+++ b/src/sentry/integrations/slack/unfurl/__init__.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import enum
-from typing import Any, Callable, Mapping, NamedTuple, Optional, Pattern
+from typing import Any, Callable, Mapping, NamedTuple, Optional, Pattern, Protocol
from django.http.request import HttpRequest
@@ -22,10 +22,21 @@ class UnfurlableUrl(NamedTuple):
args: Mapping[str, Any]
+class HandlerCallable(Protocol):
+ def __call__(
+ self,
+ request: HttpRequest,
+ integration: Integration,
+ links: list[UnfurlableUrl],
+ user: User | None = None,
+ ) -> UnfurledUrl:
+ ...
+
+
class Handler(NamedTuple):
matcher: list[Pattern[Any]]
arg_mapper: ArgsMapper
- fn: Callable[[HttpRequest, Integration, list[UnfurlableUrl], User | None], UnfurledUrl]
+ fn: HandlerCallable
def make_type_coercer(type_map: Mapping[str, type]) -> ArgsMapper:
diff --git a/src/sentry/integrations/slack/unfurl/discover.py b/src/sentry/integrations/slack/unfurl/discover.py
index 290d8677a36f19..0338d15ca7fc95 100644
--- a/src/sentry/integrations/slack/unfurl/discover.py
+++ b/src/sentry/integrations/slack/unfurl/discover.py
@@ -101,10 +101,10 @@ def is_aggregate(field: str) -> bool:
def unfurl_discover(
- data: HttpRequest,
+ request: HttpRequest,
integration: Integration,
links: list[UnfurlableUrl],
- user: User | None,
+ user: User | None = None,
) -> UnfurledUrl:
org_integrations = integration_service.get_organization_integrations(
integration_id=integration.id
@@ -148,7 +148,7 @@ def unfurl_discover(
params.setlist(
"order",
params.getlist("sort")
- or (to_list(saved_query.get("orderby")) if saved_query.get("orderby") else []),
+ or (to_list(saved_query["orderby"]) if saved_query.get("orderby") else []),
)
params.setlist("name", params.getlist("name") or to_list(saved_query.get("name")))
@@ -301,7 +301,7 @@ def map_discover_query_args(url: str, args: Mapping[str, str | None]) -> Mapping
r"^https?\://(?P<org_slug>[^.]+?)\.(?#url_prefix)[^/]+/discover/(results|homepage)"
)
-handler: Handler = Handler(
+handler = Handler(
fn=unfurl_discover,
matcher=[discover_link_regex, customer_domain_discover_link_regex],
arg_mapper=map_discover_query_args,
diff --git a/src/sentry/integrations/slack/unfurl/issues.py b/src/sentry/integrations/slack/unfurl/issues.py
index 64bcefbc02cba3..f08ed8cd7e957f 100644
--- a/src/sentry/integrations/slack/unfurl/issues.py
+++ b/src/sentry/integrations/slack/unfurl/issues.py
@@ -8,7 +8,8 @@
from sentry import eventstore
from sentry.integrations.slack.message_builder.issues import build_group_attachment
from sentry.models import Group, Project, User
-from sentry.services.hybrid_cloud.integration import RpcIntegration, integration_service
+from sentry.models.integrations.integration import Integration
+from sentry.services.hybrid_cloud.integration import integration_service
from . import Handler, UnfurlableUrl, UnfurledUrl, make_type_coercer
@@ -22,7 +23,7 @@
def unfurl_issues(
request: HttpRequest,
- integration: RpcIntegration,
+ integration: Integration,
links: List[UnfurlableUrl],
user: Optional[User] = None,
) -> UnfurledUrl:
@@ -73,7 +74,7 @@ def unfurl_issues(
r"^https?\://(?#url_prefix)[^/]+/issues/(?P<issue_id>\d+)(?:/events/(?P<event_id>\w+))?"
)
-handler: Handler = Handler(
+handler = Handler(
fn=unfurl_issues,
matcher=[issue_link_regex, customer_domain_issue_link_regex],
arg_mapper=map_issue_args,
diff --git a/src/sentry/integrations/slack/unfurl/metric_alerts.py b/src/sentry/integrations/slack/unfurl/metric_alerts.py
index 52dde47c4b9094..5c5fb1d4f2d8f7 100644
--- a/src/sentry/integrations/slack/unfurl/metric_alerts.py
+++ b/src/sentry/integrations/slack/unfurl/metric_alerts.py
@@ -145,7 +145,7 @@ def map_metric_alert_query_args(url: str, args: Mapping[str, str | None]) -> Map
r"^https?\://(?P<org_slug>[^/]+?)\.(?#url_prefix)[^/]+/alerts/rules/details/(?P<alert_rule_id>\d+)"
)
-handler: Handler = Handler(
+handler = Handler(
fn=unfurl_metric_alerts,
matcher=[metric_alerts_link_regex, customer_domain_metric_alerts_link_regex],
arg_mapper=map_metric_alert_query_args,
diff --git a/src/sentry/rules/actions/notify_event_service.py b/src/sentry/rules/actions/notify_event_service.py
index 3d54c8e4e7c20b..5f7f026546fa1e 100644
--- a/src/sentry/rules/actions/notify_event_service.py
+++ b/src/sentry/rules/actions/notify_event_service.py
@@ -1,7 +1,7 @@
from __future__ import annotations
import logging
-from typing import Any, Generator, Mapping, Sequence
+from typing import Any, Generator, Sequence
from django import forms
@@ -31,8 +31,8 @@
def build_incident_attachment(
incident: Incident,
new_status: IncidentStatus,
- metric_value: str | None = None,
-) -> Mapping[str, str]:
+ metric_value: int | None = None,
+) -> dict[str, str]:
from sentry.api.serializers.rest_framework.base import (
camel_to_snake_case,
convert_dict_key_case,
diff --git a/src/sentry/snuba/query_subscriptions/consumer.py b/src/sentry/snuba/query_subscriptions/consumer.py
index ef98630a600f37..6f094ee3ed0186 100644
--- a/src/sentry/snuba/query_subscriptions/consumer.py
+++ b/src/sentry/snuba/query_subscriptions/consumer.py
@@ -5,10 +5,7 @@
import sentry_sdk
from dateutil.parser import parse as parse_date
from sentry_kafka_schemas.codecs import Codec, ValidationError
-from sentry_kafka_schemas.schema_types.events_subscription_results_v1 import (
- PayloadV3,
- SubscriptionResult,
-)
+from sentry_kafka_schemas.schema_types.events_subscription_results_v1 import SubscriptionResult
from sentry.incidents.utils.types import SubscriptionUpdate
from sentry.snuba.dataset import EntityKey
@@ -49,7 +46,7 @@ def parse_message_value(value: bytes, jsoncodec: Codec[SubscriptionResult]) -> S
metrics.incr("snuba_query_subscriber.message_wrapper_invalid")
raise InvalidSchemaError("Message wrapper does not match schema")
- payload: PayloadV3 = wrapper["payload"]
+ payload = wrapper["payload"]
# XXX: Since we just return the raw dict here, when the payload changes it'll
# break things. This should convert the payload into a class rather than passing
# the dict around, but until we get time to refactor we can keep things working
diff --git a/tests/sentry/incidents/action_handlers/__init__.py b/tests/sentry/incidents/action_handlers/__init__.py
index db4b9199984c44..3d87a78578e6d3 100644
--- a/tests/sentry/incidents/action_handlers/__init__.py
+++ b/tests/sentry/incidents/action_handlers/__init__.py
@@ -2,9 +2,10 @@
from sentry.incidents.logic import update_incident_status
from sentry.incidents.models import Incident, IncidentStatus, IncidentStatusMethod
+from sentry.testutils.cases import TestCase
-class FireTest(abc.ABC):
+class FireTest(TestCase, abc.ABC):
@abc.abstractmethod
def run_test(self, incident: Incident, method: str, **kwargs):
pass
diff --git a/tests/sentry/incidents/action_handlers/test_email.py b/tests/sentry/incidents/action_handlers/test_email.py
index b816520ccb1991..43f60c01c0c994 100644
--- a/tests/sentry/incidents/action_handlers/test_email.py
+++ b/tests/sentry/incidents/action_handlers/test_email.py
@@ -38,7 +38,7 @@
@freeze_time()
-class EmailActionHandlerTest(FireTest, TestCase):
+class EmailActionHandlerTest(FireTest):
@responses.activate
def run_test(self, incident, method):
action = self.create_alert_rule_trigger_action(
diff --git a/tests/sentry/incidents/action_handlers/test_msteams.py b/tests/sentry/incidents/action_handlers/test_msteams.py
index ea09544e075a69..36a2d8b7d16026 100644
--- a/tests/sentry/incidents/action_handlers/test_msteams.py
+++ b/tests/sentry/incidents/action_handlers/test_msteams.py
@@ -7,7 +7,6 @@
from sentry.incidents.models import AlertRuleTriggerAction, IncidentStatus
from sentry.models import Integration
from sentry.silo import SiloMode
-from sentry.testutils.cases import TestCase
from sentry.testutils.silo import assume_test_silo_mode, region_silo_test
from sentry.utils import json
@@ -16,7 +15,7 @@
@region_silo_test(stable=True)
@freeze_time()
-class MsTeamsActionHandlerTest(FireTest, TestCase):
+class MsTeamsActionHandlerTest(FireTest):
@responses.activate
def setUp(self):
with assume_test_silo_mode(SiloMode.CONTROL):
diff --git a/tests/sentry/incidents/action_handlers/test_opsgenie.py b/tests/sentry/incidents/action_handlers/test_opsgenie.py
index 2ff7ac1de32928..b67fdc2d580b52 100644
--- a/tests/sentry/incidents/action_handlers/test_opsgenie.py
+++ b/tests/sentry/incidents/action_handlers/test_opsgenie.py
@@ -7,7 +7,6 @@
from sentry.incidents.logic import update_incident_status
from sentry.incidents.models import AlertRuleTriggerAction, IncidentStatus, IncidentStatusMethod
from sentry.models import Integration, OrganizationIntegration
-from sentry.testutils.cases import TestCase
from sentry.utils import json
from . import FireTest
@@ -20,7 +19,7 @@
@freeze_time()
-class OpsgenieActionHandlerTest(FireTest, TestCase):
+class OpsgenieActionHandlerTest(FireTest):
@responses.activate
def setUp(self):
self.og_team = {"id": "123-id", "team": "cool-team", "integration_key": "1234-5678"}
diff --git a/tests/sentry/incidents/action_handlers/test_pagerduty.py b/tests/sentry/incidents/action_handlers/test_pagerduty.py
index ed96195a3b7773..54e7041ee69a30 100644
--- a/tests/sentry/incidents/action_handlers/test_pagerduty.py
+++ b/tests/sentry/incidents/action_handlers/test_pagerduty.py
@@ -5,14 +5,13 @@
from sentry.incidents.logic import update_incident_status
from sentry.incidents.models import AlertRuleTriggerAction, IncidentStatus, IncidentStatusMethod
from sentry.models import Integration
-from sentry.testutils.cases import TestCase
from sentry.utils import json
from . import FireTest
@freeze_time()
-class PagerDutyActionHandlerTest(FireTest, TestCase):
+class PagerDutyActionHandlerTest(FireTest):
def setUp(self):
self.integration_key = "pfc73e8cb4s44d519f3d63d45b5q77g9"
service = [
diff --git a/tests/sentry/incidents/action_handlers/test_sentry_app.py b/tests/sentry/incidents/action_handlers/test_sentry_app.py
index a7c40c7f110791..0fa62301115dd7 100644
--- a/tests/sentry/incidents/action_handlers/test_sentry_app.py
+++ b/tests/sentry/incidents/action_handlers/test_sentry_app.py
@@ -3,7 +3,6 @@
from sentry.incidents.action_handlers import SentryAppActionHandler
from sentry.incidents.models import AlertRuleTriggerAction, IncidentStatus
-from sentry.testutils.cases import TestCase
from sentry.testutils.silo import region_silo_test
from sentry.utils import json
@@ -12,7 +11,7 @@
@region_silo_test(stable=True)
@freeze_time()
-class SentryAppActionHandlerTest(FireTest, TestCase):
+class SentryAppActionHandlerTest(FireTest):
def setUp(self):
self.sentry_app = self.create_sentry_app(
name="foo",
@@ -85,7 +84,7 @@ def test_resolve_metric_alert(self):
@region_silo_test(stable=True)
@freeze_time()
-class SentryAppAlertRuleUIComponentActionHandlerTest(FireTest, TestCase):
+class SentryAppAlertRuleUIComponentActionHandlerTest(FireTest):
def setUp(self):
self.sentry_app = self.create_sentry_app(
name="foo",
diff --git a/tests/sentry/incidents/action_handlers/test_slack.py b/tests/sentry/incidents/action_handlers/test_slack.py
index f048a1165ac289..d86be96989a8ec 100644
--- a/tests/sentry/incidents/action_handlers/test_slack.py
+++ b/tests/sentry/incidents/action_handlers/test_slack.py
@@ -6,7 +6,6 @@
from sentry.constants import ObjectStatus
from sentry.incidents.action_handlers import SlackActionHandler
from sentry.incidents.models import AlertRuleTriggerAction, IncidentStatus
-from sentry.testutils.cases import TestCase
from sentry.testutils.silo import region_silo_test
from sentry.utils import json
@@ -15,7 +14,7 @@
@freeze_time()
@region_silo_test(stable=True)
-class SlackActionHandlerTest(FireTest, TestCase):
+class SlackActionHandlerTest(FireTest):
@responses.activate
def setUp(self):
token = "xoxp-xxxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxx"
@@ -70,6 +69,7 @@ def run_test(self, incident, method, chart_url=None):
slack_body = SlackIncidentsMessageBuilder(
incident, IncidentStatus(incident.status), metric_value, chart_url
).build()
+ assert isinstance(slack_body, dict)
attachments = json.loads(data["attachments"][0])
assert attachments[0]["color"] == slack_body["color"]
assert attachments[0]["blocks"][0] in slack_body["blocks"]
diff --git a/tests/sentry/incidents/endpoints/test_project_alert_rule_index.py b/tests/sentry/incidents/endpoints/test_project_alert_rule_index.py
index e9a038b8ef89f2..19b8223f34699b 100644
--- a/tests/sentry/incidents/endpoints/test_project_alert_rule_index.py
+++ b/tests/sentry/incidents/endpoints/test_project_alert_rule_index.py
@@ -252,9 +252,7 @@ def test_limit_as_1_with_paging(self):
assert len(result) == 1
self.assert_alert_rule_serialized(self.yet_another_alert_rule, result[0], skip_dates=True)
- links = requests.utils.parse_header_links(
- response.get("link").rstrip(">").replace(">,<", ",<")
- )
+ links = requests.utils.parse_header_links(response["link"].rstrip(">").replace(">,<", ",<"))
next_cursor = links[1]["cursor"]
# Test Limit as 1, next page of previous request:
@@ -286,9 +284,7 @@ def test_limit_as_2_with_paging(self):
assert result[1]["id"] == str(self.issue_rule.id)
assert result[1]["type"] == "rule"
- links = requests.utils.parse_header_links(
- response.get("link").rstrip(">").replace(">,<", ",<")
- )
+ links = requests.utils.parse_header_links(response["link"].rstrip(">").replace(">,<", ",<"))
next_cursor = links[1]["cursor"]
# Test Limit 2, next page of previous request:
with self.feature(["organizations:incidents", "organizations:performance-view"]):
@@ -303,9 +299,7 @@ def test_limit_as_2_with_paging(self):
self.assert_alert_rule_serialized(self.other_alert_rule, result[0], skip_dates=True)
self.assert_alert_rule_serialized(self.alert_rule, result[1], skip_dates=True)
- links = requests.utils.parse_header_links(
- response.get("link").rstrip(">").replace(">,<", ",<")
- )
+ links = requests.utils.parse_header_links(response["link"].rstrip(">").replace(">,<", ",<"))
next_cursor = links[1]["cursor"]
# Test Limit 2, next page of previous request - should get no results since there are only 4 total:
@@ -343,9 +337,7 @@ def test_offset_pagination(self):
self.assert_alert_rule_serialized(self.three_alert_rule, result[0], skip_dates=True)
self.assert_alert_rule_serialized(self.one_alert_rule, result[1], skip_dates=True)
- links = requests.utils.parse_header_links(
- response.get("link").rstrip(">").replace(">,<", ",<")
- )
+ links = requests.utils.parse_header_links(response["link"].rstrip(">").replace(">,<", ",<"))
next_cursor = links[1]["cursor"]
assert next_cursor.split(":")[1] == "1" # Assert offset is properly calculated.
diff --git a/tests/sentry/incidents/endpoints/test_serializers.py b/tests/sentry/incidents/endpoints/test_serializers.py
index f14b7d3cd97d2e..ba6fb6bc123261 100644
--- a/tests/sentry/incidents/endpoints/test_serializers.py
+++ b/tests/sentry/incidents/endpoints/test_serializers.py
@@ -1,4 +1,7 @@
+from __future__ import annotations
+
from functools import cached_property
+from typing import Any
from unittest.mock import patch
import pytest
@@ -288,7 +291,7 @@ def test_decimal(self):
assert trigger.alert_threshold == alert_threshold
def test_simple_below_threshold(self):
- payload = {
+ payload: dict[str, Any] = {
"name": "hello_im_a_test",
"time_window": 10,
"query": "level:error",
@@ -356,7 +359,7 @@ def test_alert_rule_threshold_resolve_only(self):
assert serializer.validated_data["resolve_threshold"] == resolve_threshold
def test_boundary(self):
- payload = {
+ payload: dict[str, Any] = {
"name": "hello_im_a_test",
"time_window": 10,
"query": "level:error",
@@ -720,6 +723,7 @@ def test_enforce_max_subscriptions(self):
assert serializer.is_valid(), serializer.errors
with pytest.raises(serializers.ValidationError) as excinfo:
serializer.save()
+ assert isinstance(excinfo.value.detail, list)
assert excinfo.value.detail[0] == "You may not exceed 1 metric alerts per organization"
diff --git a/tests/sentry/incidents/test_charts.py b/tests/sentry/incidents/test_charts.py
index 281a29f5ff234c..0a3063bc076cb9 100644
--- a/tests/sentry/incidents/test_charts.py
+++ b/tests/sentry/incidents/test_charts.py
@@ -1,3 +1,5 @@
+import datetime
+
from django.utils.dateparse import parse_datetime
from freezegun import freeze_time
@@ -9,10 +11,18 @@
frozen_time = f"{now}Z"
+def must_parse_datetime(s: str) -> datetime.datetime:
+ ret = parse_datetime(s)
+ assert ret is not None
+ return ret
+
+
class IncidentDateRangeTest(TestCase):
@freeze_time(frozen_time)
def test_use_current_date_for_active_incident(self):
- incident = Incident(date_started=parse_datetime("2022-05-16T18:55:00Z"), date_closed=None)
+ incident = Incident(
+ date_started=must_parse_datetime("2022-05-16T18:55:00Z"), date_closed=None
+ )
assert incident_date_range(60, incident) == {
"start": "2022-05-16T17:40:00",
"end": now,
@@ -21,8 +31,8 @@ def test_use_current_date_for_active_incident(self):
@freeze_time(frozen_time)
def test_use_current_date_for_recently_closed_alert(self):
incident = Incident(
- date_started=parse_datetime("2022-05-16T18:55:00Z"),
- date_closed=parse_datetime("2022-05-16T18:57:00Z"),
+ date_started=must_parse_datetime("2022-05-16T18:55:00Z"),
+ date_closed=must_parse_datetime("2022-05-16T18:57:00Z"),
)
assert incident_date_range(60, incident) == {
"start": "2022-05-16T17:40:00",
@@ -33,8 +43,8 @@ def test_use_current_date_for_recently_closed_alert(self):
def test_use_a_past_date_for_an_older_alert(self):
# Incident is from over a week ago
incident = Incident(
- date_started=parse_datetime("2022-05-04T18:55:00Z"),
- date_closed=parse_datetime("2022-05-04T18:57:00Z"),
+ date_started=must_parse_datetime("2022-05-04T18:55:00Z"),
+ date_closed=must_parse_datetime("2022-05-04T18:57:00Z"),
)
assert incident_date_range(60, incident) == {
"start": "2022-05-04T17:40:00",
@@ -44,7 +54,7 @@ def test_use_a_past_date_for_an_older_alert(self):
@freeze_time(frozen_time)
def test_large_time_windows(self):
incident = Incident(
- date_started=parse_datetime("2022-04-20T20:28:00Z"),
+ date_started=must_parse_datetime("2022-04-20T20:28:00Z"),
date_closed=None,
)
one_day = 1440 * 60
diff --git a/tests/sentry/incidents/test_models.py b/tests/sentry/incidents/test_models.py
index c22ffe9bd017e7..8b498324e32a34 100644
--- a/tests/sentry/incidents/test_models.py
+++ b/tests/sentry/incidents/test_models.py
@@ -461,7 +461,7 @@ def test_specific(self):
class AlertRuleTriggerActionActivateBaseTest:
- method = None
+ method: str
def setUp(self):
self.old_handlers = AlertRuleTriggerAction._type_registrations
diff --git a/tests/sentry/incidents/test_subscription_processor.py b/tests/sentry/incidents/test_subscription_processor.py
index 90d125284d06b3..51a4dbbfc90b83 100644
--- a/tests/sentry/incidents/test_subscription_processor.py
+++ b/tests/sentry/incidents/test_subscription_processor.py
@@ -142,6 +142,10 @@ def assert_active_incident(self, rule, subscription=None):
assert incidents
return incidents[0]
+ @property
+ def sub(self):
+ raise NotImplementedError
+
def active_incident_exists(self, rule, subscription=None):
if subscription is None:
subscription = self.sub
@@ -2147,6 +2151,7 @@ def send_crash_rate_alert_update(self, rule, value, subscription, time_delta=Non
numerator = int(value * denominator)
processor.process_update(
{
+ "entity": "entity",
"subscription_id": subscription.subscription_id
if subscription
else uuid4().hex,
@@ -2160,9 +2165,6 @@ def send_crash_rate_alert_update(self, rule, value, subscription, time_delta=Non
]
},
"timestamp": timestamp,
- "interval": 1,
- "partition": 1,
- "offset": 1,
}
)
return processor
@@ -2594,6 +2596,7 @@ def test_ensure_case_when_no_metrics_index_not_found_is_handled_gracefully(self)
processor = SubscriptionProcessor(subscription)
processor.process_update(
{
+ "entity": "entity",
"subscription_id": subscription.subscription_id,
"values": {
# 1001 is a random int that doesn't map to anything in the indexer
@@ -2606,9 +2609,6 @@ def test_ensure_case_when_no_metrics_index_not_found_is_handled_gracefully(self)
]
},
"timestamp": timezone.now(),
- "interval": 1,
- "partition": 1,
- "offset": 1,
}
)
self.assert_no_active_incident(rule)
@@ -2661,6 +2661,7 @@ def send_crash_rate_alert_update(self, rule, value, subscription, time_delta=Non
tag_value_crashed = resolve_tag_value(UseCaseKey.RELEASE_HEALTH, org_id, "crashed")
processor.process_update(
{
+ "entity": "entity",
"subscription_id": subscription.subscription_id
if subscription
else uuid4().hex,
@@ -2675,9 +2676,6 @@ def send_crash_rate_alert_update(self, rule, value, subscription, time_delta=Non
]
},
"timestamp": timestamp,
- "interval": 1,
- "partition": 1,
- "offset": 1,
}
)
return processor
diff --git a/tests/sentry/incidents/test_tasks.py b/tests/sentry/incidents/test_tasks.py
index ccf17cd9fbe341..5dc12244f2ad51 100644
--- a/tests/sentry/incidents/test_tasks.py
+++ b/tests/sentry/incidents/test_tasks.py
@@ -44,13 +44,13 @@
pytestmark = pytest.mark.sentry_metrics
-class BaseIncidentActivityTest:
+class BaseIncidentActivityTest(TestCase):
@property
def incident(self):
return self.create_incident(title="hello")
-class TestSendSubscriberNotifications(BaseIncidentActivityTest, TestCase):
+class TestSendSubscriberNotifications(BaseIncidentActivityTest):
@pytest.fixture(autouse=True)
def _setup_send_async_patch(self):
with mock.patch("sentry.utils.email.MessageBuilder.send_async") as self.send_async:
@@ -89,7 +89,7 @@ def test_invalid_types(self):
@region_silo_test(stable=True)
-class TestGenerateIncidentActivityEmail(BaseIncidentActivityTest, TestCase):
+class TestGenerateIncidentActivityEmail(BaseIncidentActivityTest):
@freeze_time()
def test_simple(self):
activity = create_incident_activity(
@@ -104,7 +104,7 @@ def test_simple(self):
@region_silo_test(stable=True)
-class TestBuildActivityContext(BaseIncidentActivityTest, TestCase):
+class TestBuildActivityContext(BaseIncidentActivityTest):
def run_test(
self, activity, expected_username, expected_action, expected_comment, expected_recipient
):
@@ -136,9 +136,11 @@ def test_simple(self):
self.incident, IncidentActivityType.COMMENT, user=self.user, comment="hello"
)
recipient = self.create_user()
+ user = user_service.get_user(user_id=activity.user_id)
+ assert user is not None
self.run_test(
activity,
- expected_username=user_service.get_user(user_id=activity.user_id).name,
+ expected_username=user.name,
expected_action="left a comment",
expected_comment=activity.comment,
expected_recipient=recipient,
@@ -146,9 +148,11 @@ def test_simple(self):
activity.type = IncidentActivityType.STATUS_CHANGE
activity.value = str(IncidentStatus.CLOSED.value)
activity.previous_value = str(IncidentStatus.WARNING.value)
+ user = user_service.get_user(user_id=activity.user_id)
+ assert user is not None
self.run_test(
activity,
- expected_username=user_service.get_user(user_id=activity.user_id).name,
+ expected_username=user.name,
expected_action="changed status from %s to %s"
% (INCIDENT_STATUS[IncidentStatus.WARNING], INCIDENT_STATUS[IncidentStatus.CLOSED]),
expected_comment=activity.comment,
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 fc5706a0790bcb..fb92842f7691bd 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,3 +1,5 @@
+from __future__ import annotations
+
from datetime import datetime, timezone
from unittest import mock
@@ -22,7 +24,8 @@ def test_outcomes_consumed(track_outcome):
topic = Topic("snuba-generic-metrics")
- buckets = [
+ empty_tags: dict[str, str] = {}
+ buckets: list[MetricsBucket] = [
{ # Counter metric with wrong ID will not generate an outcome
"metric_id": 123,
"type": "c",
@@ -30,7 +33,7 @@ def test_outcomes_consumed(track_outcome):
"project_id": 2,
"timestamp": 123,
"value": 123.4,
- "tags": {},
+ "tags": empty_tags,
},
{ # Distribution metric with wrong ID will not generate an outcome
"metric_id": 123,
@@ -39,7 +42,7 @@ def test_outcomes_consumed(track_outcome):
"project_id": 2,
"timestamp": 123456,
"value": [1.0, 2.0],
- "tags": {},
+ "tags": empty_tags,
},
{ # Empty distribution will not generate an outcome
# NOTE: Should not be emitted by Relay anyway
@@ -49,7 +52,7 @@ def test_outcomes_consumed(track_outcome):
"project_id": 2,
"timestamp": 123456,
"value": [],
- "tags": {},
+ "tags": empty_tags,
},
{ # Valid distribution bucket emits an outcome
"metric_id": TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"],
@@ -58,7 +61,7 @@ def test_outcomes_consumed(track_outcome):
"project_id": 2,
"timestamp": 123456,
"value": [1.0, 2.0, 3.0],
- "tags": {},
+ "tags": empty_tags,
},
{ # Another bucket to introduce some noise
"metric_id": 123,
@@ -67,7 +70,7 @@ def test_outcomes_consumed(track_outcome):
"project_id": 2,
"timestamp": 123456,
"value": 123.4,
- "tags": {},
+ "tags": empty_tags,
},
{ # Bucket with profiles
"metric_id": TRANSACTION_METRICS_NAMES["d:transactions/duration@millisecond"],
@@ -86,22 +89,24 @@ def test_outcomes_consumed(track_outcome):
commit=fake_commit,
)
+ generate_kafka_message_counter = 0
+
def generate_kafka_message(bucket: MetricsBucket) -> Message[KafkaPayload]:
+ nonlocal generate_kafka_message_counter
+
encoded = json.dumps(bucket).encode()
payload = KafkaPayload(key=None, value=encoded, headers=[])
message = Message(
BrokerValue(
payload,
Partition(topic, index=0),
- generate_kafka_message.counter,
+ generate_kafka_message_counter,
datetime.now(timezone.utc),
)
)
- generate_kafka_message.counter += 1
+ generate_kafka_message_counter += 1
return message
- generate_kafka_message.counter = 0
-
# Mimick the behavior of StreamProcessor._run_once: Call poll repeatedly,
# then call submit when there is a message.
strategy.poll()
diff --git a/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py b/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
index 2fe5fa65d7902c..edc39167dfe6f1 100644
--- a/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
+++ b/tests/sentry/ingest/ingest_consumer/test_ingest_consumer_kafka.py
@@ -171,7 +171,7 @@ def test_ingest_topic_can_be_overridden(
consumer_type=ConsumerType.Events,
group_id=random_group_id,
auto_offset_reset="earliest",
- strict_offset_reset=None,
+ strict_offset_reset=False,
max_batch_size=2,
max_batch_time=5,
num_processes=1,
diff --git a/tests/sentry/ingest/test_span_desc_clusterer.py b/tests/sentry/ingest/test_span_desc_clusterer.py
index 48aac9acd31d08..092c1fe0e9d8a5 100644
--- a/tests/sentry/ingest/test_span_desc_clusterer.py
+++ b/tests/sentry/ingest/test_span_desc_clusterer.py
@@ -161,7 +161,11 @@ def test_record_span_desc_url(mocked_record, default_organization):
def test_sort_rules():
- rules = {"/a/*/**": 1, "/a/**": 2, "/a/*/c/**": 3}
+ rules = {
+ ReplacementRule("/a/*/**"): 1,
+ ReplacementRule("/a/**"): 2,
+ ReplacementRule("/a/*/c/**"): 3,
+ }
assert ProjectOptionRuleStore(ClustererNamespace.SPANS)._sort(rules) == [
("/a/*/c/**", 3),
("/a/*/**", 1),
@@ -342,8 +346,7 @@ def test_span_descs_clusterer_generates_rules(default_project):
def _get_projconfig_span_desc_rules(project: Project):
return (
get_project_config(project, full_config=True)
- .to_dict()
- .get("config")
+ .to_dict()["config"]
.get("spanDescriptionRules")
)
@@ -353,7 +356,7 @@ def _get_projconfig_span_desc_rules(project: Project):
with Feature({feature: True}):
assert _get_projconfig_span_desc_rules(default_project) is None
- rules = {"/rule/*/0/**": 0, "/rule/*/1/**": 1}
+ rules = {ReplacementRule("/rule/*/0/**"): 0, ReplacementRule("/rule/*/1/**"): 1}
ProjectOptionRuleStore(ClustererNamespace.SPANS).write(default_project, rules)
with Feature({feature: False}):
@@ -518,7 +521,9 @@ def test_stale_rules_arent_saved(default_project):
def test_bump_last_used():
"""Redis update works and does not delete other keys in the set."""
project1 = Project(id=123, name="project1")
- RedisRuleStore(namespace=ClustererNamespace.SPANS).write(project1, {"foo": 1, "bar": 2})
+ RedisRuleStore(namespace=ClustererNamespace.SPANS).write(
+ project1, {ReplacementRule("foo"): 1, ReplacementRule("bar"): 2}
+ )
assert get_redis_rules(ClustererNamespace.SPANS, project1) == {"foo": 1, "bar": 2}
with freeze_time("2000-01-01 01:00:00"):
bump_last_used(ClustererNamespace.SPANS, project1, "bar")
diff --git a/tests/sentry/ingest/test_transaction_clusterer.py b/tests/sentry/ingest/test_transaction_clusterer.py
index 1a037038eef1ce..c5da9efeb5e965 100644
--- a/tests/sentry/ingest/test_transaction_clusterer.py
+++ b/tests/sentry/ingest/test_transaction_clusterer.py
@@ -174,7 +174,11 @@ def test_record_transactions(mocked_record, default_organization, source, txname
def test_sort_rules():
- rules = {"/a/*/**": 1, "/a/**": 2, "/a/*/c/**": 3}
+ rules = {
+ ReplacementRule("/a/*/**"): 1,
+ ReplacementRule("/a/**"): 2,
+ ReplacementRule("/a/*/c/**"): 3,
+ }
assert ProjectOptionRuleStore(ClustererNamespace.TRANSACTIONS)._sort(rules) == [
("/a/*/c/**", 3),
("/a/*/**", 1),
@@ -351,9 +355,7 @@ def test_get_deleted_project():
@django_db_all
def test_transaction_clusterer_generates_rules(default_project):
def _get_projconfig_tx_rules(project: Project):
- return (
- get_project_config(project, full_config=True).to_dict().get("config").get("txNameRules")
- )
+ return get_project_config(project, full_config=True).to_dict()["config"].get("txNameRules")
feature = "organizations:transaction-name-normalize"
with Feature({feature: False}):
@@ -361,7 +363,7 @@ def _get_projconfig_tx_rules(project: Project):
with Feature({feature: True}):
assert _get_projconfig_tx_rules(default_project) is None
- rules = {"/rule/*/0/**": 0, "/rule/*/1/**": 1}
+ rules = {ReplacementRule("/rule/*/0/**"): 0, ReplacementRule("/rule/*/1/**"): 1}
ProjectOptionRuleStore(ClustererNamespace.TRANSACTIONS).write(default_project, rules)
with Feature({feature: False}):
@@ -502,7 +504,9 @@ def test_stale_rules_arent_saved(default_project):
def test_bump_last_used():
"""Redis update works and does not delete other keys in the set."""
project1 = Project(id=123, name="project1")
- RedisRuleStore(namespace=ClustererNamespace.TRANSACTIONS).write(project1, {"foo": 1, "bar": 2})
+ RedisRuleStore(namespace=ClustererNamespace.TRANSACTIONS).write(
+ project1, {ReplacementRule("foo"): 1, ReplacementRule("bar"): 2}
+ )
assert get_redis_rules(ClustererNamespace.TRANSACTIONS, project1) == {"foo": 1, "bar": 2}
with freeze_time("2000-01-01 01:00:00"):
bump_last_used(ClustererNamespace.TRANSACTIONS, project1, "bar")
diff --git a/tests/sentry/ingest/test_transaction_rule_validator.py b/tests/sentry/ingest/test_transaction_rule_validator.py
index 6e5386b95ecbc3..818ef5beadafb2 100644
--- a/tests/sentry/ingest/test_transaction_rule_validator.py
+++ b/tests/sentry/ingest/test_transaction_rule_validator.py
@@ -1,23 +1,24 @@
+from sentry.ingest.transaction_clusterer.base import ReplacementRule
from sentry.ingest.transaction_clusterer.rule_validator import RuleValidator
def test_all_star_rules_invalid():
- assert not RuleValidator("*/**").is_valid()
- assert not RuleValidator("/*/**").is_valid()
+ assert not RuleValidator(ReplacementRule("*/**")).is_valid()
+ assert not RuleValidator(ReplacementRule("/*/**")).is_valid()
- assert not RuleValidator("*/*/*/*/**").is_valid()
- assert not RuleValidator("/*/*/*/*/**").is_valid()
+ assert not RuleValidator(ReplacementRule("*/*/*/*/**")).is_valid()
+ assert not RuleValidator(ReplacementRule("/*/*/*/*/**")).is_valid()
def test_non_all_star_rules_valid():
- assert RuleValidator("a/*/**").is_valid()
- assert RuleValidator("/a/*/**").is_valid()
+ assert RuleValidator(ReplacementRule("a/*/**")).is_valid()
+ assert RuleValidator(ReplacementRule("/a/*/**")).is_valid()
- assert RuleValidator("*/a/**").is_valid()
- assert RuleValidator("/*/a/**").is_valid()
+ assert RuleValidator(ReplacementRule("*/a/**")).is_valid()
+ assert RuleValidator(ReplacementRule("/*/a/**")).is_valid()
- assert RuleValidator("a/*/b/**").is_valid()
- assert RuleValidator("/a/*/b/**").is_valid()
+ assert RuleValidator(ReplacementRule("a/*/b/**")).is_valid()
+ assert RuleValidator(ReplacementRule("/a/*/b/**")).is_valid()
- assert RuleValidator("a/*/b/*/c/**").is_valid()
- assert RuleValidator("/a/*/b/*/c/**").is_valid()
+ assert RuleValidator(ReplacementRule("a/*/b/*/c/**")).is_valid()
+ assert RuleValidator(ReplacementRule("/a/*/b/*/c/**")).is_valid()
diff --git a/tests/sentry/integrations/bitbucket/test_installed.py b/tests/sentry/integrations/bitbucket/test_installed.py
index 9c7a0ed425f6ff..a985e956e81c61 100644
--- a/tests/sentry/integrations/bitbucket/test_installed.py
+++ b/tests/sentry/integrations/bitbucket/test_installed.py
@@ -1,3 +1,7 @@
+from __future__ import annotations
+
+from typing import Any
+
import responses
from sentry.integrations.bitbucket.installed import BitbucketInstalledEndpoint
@@ -68,7 +72,7 @@ def setUp(self):
self.user_metadata["type"] = self.user_data["type"]
self.user_metadata["domain_name"] = self.user_display_name
- self.team_data_from_bitbucket = {
+ self.team_data_from_bitbucket: dict[str, Any] = {
"key": "sentry-bitbucket",
"eventType": "installed",
"baseUrl": self.base_url,
diff --git a/tests/sentry/integrations/bitbucket/test_issues.py b/tests/sentry/integrations/bitbucket/test_issues.py
index 3384fa15e3723a..c4b337b2446bbc 100644
--- a/tests/sentry/integrations/bitbucket/test_issues.py
+++ b/tests/sentry/integrations/bitbucket/test_issues.py
@@ -29,9 +29,11 @@ def setUp(self):
"subject": self.subject,
},
)
- self.org_integration = integration_service.get_organization_integration(
+ org_integration = integration_service.get_organization_integration(
integration_id=self.integration.id, organization_id=self.organization.id
)
+ assert org_integration is not None
+ self.org_integration = org_integration
min_ago = iso_format(before_now(minutes=1))
event = self.store_event(
data={
diff --git a/tests/sentry/integrations/github/test_client.py b/tests/sentry/integrations/github/test_client.py
index 50d58921a0f774..0f63e346dac5ab 100644
--- a/tests/sentry/integrations/github/test_client.py
+++ b/tests/sentry/integrations/github/test_client.py
@@ -10,8 +10,10 @@
from responses import matchers
from sentry.integrations.github.client import GitHubAppsClient
+from sentry.integrations.github.integration import GitHubIntegration
from sentry.models import Repository
from sentry.shared_integrations.exceptions import ApiError
+from sentry.shared_integrations.response.base import BaseApiResponse
from sentry.silo.base import SiloMode
from sentry.silo.util import PROXY_BASE_PATH, PROXY_OI_HEADER, PROXY_SIGNATURE_HEADER
from sentry.testutils.cases import TestCase
@@ -42,8 +44,10 @@ def setUp(self, get_jwt):
external_id=123,
integration_id=integration.id,
)
- self.install = integration.get_installation(organization_id=self.organization.id)
- self.client = self.install.get_client()
+ install = integration.get_installation(organization_id=self.organization.id)
+ assert isinstance(install, GitHubIntegration)
+ self.install = install
+ self.github_client = self.install.get_client()
responses.add(
method=responses.POST,
url="https://api.github.com/app/installations/1/access_tokens",
@@ -66,19 +70,19 @@ def test_get_rate_limit(self):
},
)
with mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1"):
- gh_rate_limit = self.client.get_rate_limit()
+ gh_rate_limit = self.github_client.get_rate_limit()
assert gh_rate_limit.limit == 5000
assert gh_rate_limit.remaining == 4999
assert gh_rate_limit.used == 1
assert gh_rate_limit.next_window() == "17:47:53"
- gh_rate_limit = self.client.get_rate_limit("search")
+ gh_rate_limit = self.github_client.get_rate_limit("search")
assert gh_rate_limit.limit == 30
assert gh_rate_limit.remaining == 18
assert gh_rate_limit.used == 12
assert gh_rate_limit.next_window() == "16:50:52"
- gh_rate_limit = self.client.get_rate_limit("graphql")
+ gh_rate_limit = self.github_client.get_rate_limit("graphql")
assert gh_rate_limit.limit == 5000
assert gh_rate_limit.remaining == 4993
assert gh_rate_limit.used == 7
@@ -86,7 +90,7 @@ def test_get_rate_limit(self):
def test_get_rate_limit_non_existant_resouce(self):
with pytest.raises(AssertionError):
- self.client.get_rate_limit("foo")
+ self.github_client.get_rate_limit("foo")
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
@@ -101,7 +105,8 @@ def test_check_file(self, get_jwt):
json={"text": 200},
)
- resp = self.client.check_file(self.repo, path, version)
+ resp = self.github_client.check_file(self.repo, path, version)
+ assert isinstance(resp, BaseApiResponse)
assert resp.status_code == 200
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@@ -114,7 +119,7 @@ def test_check_no_file(self, get_jwt):
responses.add(method=responses.HEAD, url=url, status=404)
with pytest.raises(ApiError):
- self.client.check_file(self.repo, path, version)
+ self.github_client.check_file(self.repo, path, version)
assert responses.calls[1].response.status_code == 404
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@@ -141,7 +146,7 @@ def test_get_stacktrace_link(self, get_jwt):
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_get_with_pagination(self, get_jwt):
- url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.client.page_size}"
+ url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.github_client.page_size}"
responses.add(
method=responses.GET,
@@ -170,18 +175,18 @@ def test_get_with_pagination(self, get_jwt):
# The code only cares about the `next` value which is not included here
headers={"link": f'<{url}&page=1>; rel="first", <{url}&page=3>; rel="prev"'},
)
- self.client.get_with_pagination(f"/repos/{self.repo.name}/assignees")
+ self.github_client.get_with_pagination(f"/repos/{self.repo.name}/assignees")
assert len(responses.calls) == 5
assert responses.calls[1].response.status_code == 200
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@responses.activate
def test_get_with_pagination_only_one_page(self, get_jwt):
- url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.client.page_size}"
+ url = f"https://api.github.com/repos/{self.repo.name}/assignees?per_page={self.github_client.page_size}"
# No link in the headers because there are no more pages
responses.add(method=responses.GET, url=url, json={}, headers={})
- self.client.get_with_pagination(f"/repos/{self.repo.name}/assignees")
+ self.github_client.get_with_pagination(f"/repos/{self.repo.name}/assignees")
# One call is for getting the token for the installation
assert len(responses.calls) == 2
assert responses.calls[1].response.status_code == 200
@@ -246,7 +251,7 @@ def test_get_blame_for_file(self, get_jwt):
json={"query": query, "data": {"repository": {"ref": {"target": {}}}}},
content_type="application/json",
)
- resp = self.client.get_blame_for_file(self.repo, path, ref, 1)
+ resp = self.github_client.get_blame_for_file(self.repo, path, ref, 1)
assert (
responses.calls[1].request.body
== b'{"query": "query {\\n repository(name: \\"foo\\", owner: \\"Test-Organization\\") {\\n ref(qualifiedName: \\"master\\") {\\n target {\\n ... on Commit {\\n blame(path: \\"src/sentry/integrations/github/client.py\\") {\\n ranges {\\n commit {\\n oid\\n author {\\n name\\n email\\n }\\n message\\n committedDate\\n }\\n startingLine\\n endingLine\\n age\\n }\\n }\\n }\\n }\\n }\\n }\\n }"}'
@@ -264,7 +269,7 @@ def test_get_blame_for_file_graphql_errors(self, get_jwt):
content_type="application/json",
)
with pytest.raises(ApiError) as excinfo:
- self.client.get_blame_for_file(self.repo, "foo.py", "main", 1)
+ self.github_client.get_blame_for_file(self.repo, "foo.py", "main", 1)
(msg,) = excinfo.value.args
assert msg == "something, went wrong"
@@ -278,7 +283,7 @@ def test_get_blame_for_file_graphql_no_branch(self, get_jwt):
content_type="application/json",
)
with pytest.raises(ApiError) as excinfo:
- self.client.get_blame_for_file(self.repo, "foo.py", "main", 1)
+ self.github_client.get_blame_for_file(self.repo, "foo.py", "main", 1)
(msg,) = excinfo.value.args
assert msg == "Branch does not exist in GitHub."
@@ -294,14 +299,14 @@ def test_get_cached_repo_files_caching_functionality(self):
repo_key = f"github:repo:{self.repo.name}:source-code"
assert cache.get(repo_key) is None
with mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1"):
- files = self.client.get_cached_repo_files(self.repo.name, "master")
+ files = self.github_client.get_cached_repo_files(self.repo.name, "master")
assert cache.get(repo_key) == files
# Calling a second time should work
- files = self.client.get_cached_repo_files(self.repo.name, "master")
+ files = self.github_client.get_cached_repo_files(self.repo.name, "master")
assert cache.get(repo_key) == files
# Calling again after the cache has been cleared should still work
cache.delete(repo_key)
- files = self.client.get_cached_repo_files(self.repo.name, "master")
+ files = self.github_client.get_cached_repo_files(self.repo.name, "master")
assert cache.get(repo_key) == files
@responses.activate
@@ -321,7 +326,7 @@ def test_get_cached_repo_files_with_all_files(self):
repo_key = f"github:repo:{self.repo.name}:all"
assert cache.get(repo_key) is None
with mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1"):
- files = self.client.get_cached_repo_files(self.repo.name, "master")
+ files = self.github_client.get_cached_repo_files(self.repo.name, "master")
assert files == ["src/foo.py"]
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=b"jwt_token_1")
@@ -343,7 +348,7 @@ def test_update_comment(self, get_jwt):
"author_association": "COLLABORATOR",
},
)
- self.client.create_comment(repo=self.repo.name, issue_id="1", data={"body": "hello"})
+ self.github_client.create_comment(repo=self.repo.name, issue_id="1", data={"body": "hello"})
responses.add(
method=responses.PATCH,
@@ -361,7 +366,9 @@ def test_update_comment(self, get_jwt):
},
)
- self.client.update_comment(repo=self.repo.name, comment_id="1", data={"body": "world"})
+ self.github_client.update_comment(
+ repo=self.repo.name, comment_id="1", data={"body": "world"}
+ )
assert responses.calls[2].response.status_code == 200
assert responses.calls[2].request.body == b'{"body": "world"}'
@@ -382,7 +389,7 @@ def test_get_comment_reactions(self, get_jwt):
json=comment_reactions,
)
- reactions = self.client.get_comment_reactions(repo=self.repo.name, comment_id="2")
+ reactions = self.github_client.get_comment_reactions(repo=self.repo.name, comment_id="2")
stored_reactions = comment_reactions["reactions"]
del stored_reactions["url"]
assert reactions == stored_reactions
@@ -423,15 +430,16 @@ def setUp(self):
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
def test__refresh_access_token(self, mock_jwt):
- assert self.integration.metadata["access_token"] is not self.access_token
- assert self.integration.metadata["expires_at"] is None
+ assert self.integration.metadata == {"access_token": None, "expires_at": None}
self.gh_client._refresh_access_token()
assert mock_jwt.called
self.integration.refresh_from_db()
- assert self.integration.metadata["access_token"] == self.access_token
- assert self.integration.metadata["expires_at"] in self.expires_at
+ assert self.integration.metadata == {
+ "access_token": self.access_token,
+ "expires_at": self.expires_at.rstrip("Z"),
+ }
@responses.activate
@mock.patch("sentry.integrations.github.client.get_jwt", return_value=jwt)
@@ -499,7 +507,7 @@ def test_authorize_request_valid(self, mock_jwt):
assert self.access_token in access_token_request.headers["Authorization"]
mock_jwt.reset_mock()
- access_token_request.headers = {}
+ access_token_request.headers.clear()
# Following requests should just add headers
self.gh_client.authorize_request(prepared_request=access_token_request)
diff --git a/tests/sentry/integrations/github/test_integration.py b/tests/sentry/integrations/github/test_integration.py
index 0359d8686ccbb6..f0b161f8aea703 100644
--- a/tests/sentry/integrations/github/test_integration.py
+++ b/tests/sentry/integrations/github/test_integration.py
@@ -1,13 +1,23 @@
-from unittest.mock import MagicMock, patch
+from __future__ import annotations
+
+from typing import Any
+from unittest import mock
+from unittest.mock import patch
from urllib.parse import urlencode, urlparse
+import pytest
import responses
from django.urls import reverse
import sentry
from sentry.api.utils import generate_organization_url
from sentry.constants import ObjectStatus
-from sentry.integrations.github import API_ERRORS, MINIMUM_REQUESTS, GitHubIntegrationProvider
+from sentry.integrations.github import (
+ API_ERRORS,
+ MINIMUM_REQUESTS,
+ GitHubIntegrationProvider,
+ client,
+)
from sentry.integrations.utils.code_mapping import Repo, RepoTree
from sentry.models import Integration, OrganizationIntegration, Project, Repository
from sentry.plugins.base import plugins
@@ -85,11 +95,14 @@ def tearDown(self):
plugins.unregister(GitHubPlugin)
super().tearDown()
+ @pytest.fixture(autouse=True)
+ def stub_get_jwt(self):
+ with mock.patch.object(client, "get_jwt", return_value="jwt_token_1"):
+ yield
+
def _stub_github(self):
"""This stubs the calls related to a Github App"""
self.gh_org = "Test-Organization"
- sentry.integrations.github.integration.get_jwt = MagicMock(return_value="jwt_token_1")
- sentry.integrations.github.client.get_jwt = MagicMock(return_value="jwt_token_1")
pp = 1
responses.add(
@@ -98,7 +111,7 @@ def _stub_github(self):
json={"token": self.access_token, "expires_at": self.expires_at},
)
- repositories = {
+ repositories: dict[str, Any] = {
"xyz": {
"full_name": "Test-Organization/xyz",
"default_branch": "master",
diff --git a/tests/sentry/integrations/github/test_issues.py b/tests/sentry/integrations/github/test_issues.py
index be35f2b2d7f4a5..87f07244e818a4 100644
--- a/tests/sentry/integrations/github/test_issues.py
+++ b/tests/sentry/integrations/github/test_issues.py
@@ -119,15 +119,15 @@ def test_generic_issues_content(self):
},
project_id=self.project.id,
)
- event = event.for_group(event.groups[0])
- event.occurrence = occurrence
+ group_event = event.for_group(event.groups[0])
+ group_event.occurrence = occurrence
- description = GitHubIssueBasic().get_group_description(event.group, event)
- assert event.occurrence.evidence_display[0].value in description
- assert event.occurrence.evidence_display[1].value in description
- assert event.occurrence.evidence_display[2].value in description
- title = GitHubIssueBasic().get_group_title(event.group, event)
- assert title == event.occurrence.issue_title
+ description = GitHubIssueBasic().get_group_description(group_event.group, group_event)
+ assert group_event.occurrence.evidence_display[0].value in description
+ assert group_event.occurrence.evidence_display[1].value in description
+ assert group_event.occurrence.evidence_display[2].value in description
+ title = GitHubIssueBasic().get_group_title(group_event.group, group_event)
+ assert title == group_event.occurrence.issue_title
def test_error_issues_content(self):
"""Test that a GitHub issue created from an error issue has the expected title and descriptionn"""
@@ -139,6 +139,7 @@ def test_error_issues_content(self):
},
project_id=self.project.id,
)
+ assert event.group is not None
description = GitHubIssueBasic().get_group_description(event.group, event)
assert "oh no" in description
@@ -305,6 +306,7 @@ def test_default_repo_link_fields(self, mock_get_jwt):
event = self.store_event(
data={"event_id": "a" * 32, "timestamp": self.min_ago}, project_id=self.project.id
)
+ assert event.group is not None
group = event.group
integration_service.update_organization_integration(
org_integration_id=self.integration.org_integration.id,
@@ -343,6 +345,7 @@ def test_default_repo_create_fields(self, mock_get_jwt):
event = self.store_event(
data={"event_id": "a" * 32, "timestamp": self.min_ago}, project_id=self.project.id
)
+ assert event.group is not None
group = event.group
integration_service.update_organization_integration(
org_integration_id=self.integration.org_integration.id,
diff --git a/tests/sentry/integrations/gitlab/test_client.py b/tests/sentry/integrations/gitlab/test_client.py
index 72445bde4d02f2..5df254b8e629bc 100644
--- a/tests/sentry/integrations/gitlab/test_client.py
+++ b/tests/sentry/integrations/gitlab/test_client.py
@@ -24,8 +24,8 @@ class GitlabRefreshAuthTest(GitLabTestCase):
def setUp(self):
super().setUp()
- self.client = self.installation.get_client()
- self.client.base_url = "https://example.gitlab.com/"
+ self.gitlab_client = self.installation.get_client()
+ self.gitlab_client.base_url = "https://example.gitlab.com/"
self.request_data = {"id": "user_id"}
self.request_url = "https://example.gitlab.com/api/v4/user"
self.refresh_url = "https://example.gitlab.com/oauth/token"
@@ -37,14 +37,14 @@ def setUp(self):
"scope": "api",
}
self.repo = self.create_repo(name="Test-Org/foo", external_id=123)
- self.original_identity_data = dict(self.client.identity.data)
+ self.original_identity_data = dict(self.gitlab_client.identity.data)
self.gitlab_id = 123
def tearDown(self):
responses.reset()
def make_users_request(self):
- return self.client.get_user()
+ return self.gitlab_client.get_user()
def add_refresh_auth(self, success=True):
responses.add(
@@ -89,17 +89,17 @@ def assert_request_with_refresh(self):
assert json.loads(responses_calls[2].response.text) == self.request_data
def assert_identity_was_refreshed(self):
- data = self.client.identity.data
+ data = self.gitlab_client.identity.data
self.assert_data(data, self.refresh_response)
- data = Identity.objects.get(id=self.client.identity.id).data
+ data = Identity.objects.get(id=self.gitlab_client.identity.id).data
self.assert_data(data, self.refresh_response)
def assert_identity_was_not_refreshed(self):
- data = self.client.identity.data
+ data = self.gitlab_client.identity.data
self.assert_data(data, self.original_identity_data)
- data = Identity.objects.get(id=self.client.identity.id).data
+ data = Identity.objects.get(id=self.gitlab_client.identity.id).data
self.assert_data(data, self.original_identity_data)
@responses.activate
@@ -147,7 +147,7 @@ def test_check_file(self):
json={"text": 200},
)
- resp = self.client.check_file(self.repo, path, ref)
+ resp = self.gitlab_client.check_file(self.repo, path, ref)
assert responses.calls[0].response.status_code == 200
assert resp.status_code == 200
@@ -161,7 +161,7 @@ def test_check_no_file(self):
status=404,
)
with pytest.raises(ApiError):
- self.client.check_file(self.repo, path, ref)
+ self.gitlab_client.check_file(self.repo, path, ref)
assert responses.calls[0].response.status_code == 404
@responses.activate
@@ -210,5 +210,5 @@ def test_get_commit(self):
json=json.loads(GET_COMMIT_RESPONSE),
)
- resp = self.client.get_commit(self.gitlab_id, commit)
+ resp = self.gitlab_client.get_commit(self.gitlab_id, commit)
assert resp == json.loads(GET_COMMIT_RESPONSE)
diff --git a/tests/sentry/integrations/gitlab/test_integration.py b/tests/sentry/integrations/gitlab/test_integration.py
index 978559fae4793f..39ed558f8b8d39 100644
--- a/tests/sentry/integrations/gitlab/test_integration.py
+++ b/tests/sentry/integrations/gitlab/test_integration.py
@@ -1,6 +1,7 @@
from unittest.mock import Mock, patch
from urllib.parse import parse_qs, quote, urlencode, urlparse
+import pytest
import responses
from django.core.cache import cache
from django.test import override_settings
@@ -16,6 +17,7 @@
OrganizationIntegration,
Repository,
)
+from sentry.shared_integrations.exceptions import ApiUnauthorized
from sentry.silo.base import SiloMode
from sentry.silo.util import PROXY_BASE_PATH, PROXY_OI_HEADER, PROXY_SIGNATURE_HEADER
from sentry.testutils.cases import IntegrationTestCase
@@ -301,13 +303,9 @@ def test_get_stacktrace_link_file_identity_not_valid(self):
json={},
)
- try:
+ with pytest.raises(ApiUnauthorized) as excinfo:
installation.get_stacktrace_link(repo, "README.md", ref, version)
- except Exception as e:
- assert e.code == 401
- else:
- # check that the call throws.
- assert False
+ assert excinfo.value.code == 401
@responses.activate
def test_get_stacktrace_link_use_default_if_version_404(self):
diff --git a/tests/sentry/integrations/jira/test_client.py b/tests/sentry/integrations/jira/test_client.py
index 97f99b2ac0ac92..7a465382791ddd 100644
--- a/tests/sentry/integrations/jira/test_client.py
+++ b/tests/sentry/integrations/jira/test_client.py
@@ -46,7 +46,7 @@ def setUp(self):
)
self.integration.add_organization(self.organization, self.user)
install = self.integration.get_installation(self.organization.id)
- self.client = install.get_client()
+ self.jira_client = install.get_client()
@responses.activate
@mock.patch(
@@ -66,7 +66,7 @@ def test_get_field_autocomplete_for_non_customfield(self, mock_authorize):
status=200,
content_type="application/json",
)
- res = self.client.get_field_autocomplete("my_field", "abc")
+ res = self.jira_client.get_field_autocomplete("my_field", "abc")
assert res == body
@responses.activate
@@ -87,7 +87,7 @@ def test_get_field_autocomplete_for_customfield(self, mock_authorize):
status=200,
content_type="application/json",
)
- res = self.client.get_field_autocomplete("customfield_0123", "abc")
+ res = self.jira_client.get_field_autocomplete("customfield_0123", "abc")
assert res == body
@freeze_time("2023-01-01 01:01:01")
@@ -96,10 +96,10 @@ def test_authorize_request(self):
params = {"query": "1", "user": "me"}
request = Request(
method=method,
- url=f"{self.client.base_url}{self.client.SERVER_INFO_URL}",
+ url=f"{self.jira_client.base_url}{self.jira_client.SERVER_INFO_URL}",
params=params,
).prepare()
- self.client.authorize_request(prepared_request=request)
+ self.jira_client.authorize_request(prepared_request=request)
raw_jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJ0ZXN0c2VydmVyLmppcmEiLCJpYXQiOjE2NzI1MzQ4NjEsImV4cCI6MTY3MjUzNTE2MSwicXNoIjoiZGU5NTIwMTA2NDBhYjJjZmQyMDYyNzgxYjU0ZTk0Yjc4ZmNlMTY3MzEwMDZkYjdkZWVhZmZjZWI0MjVmZTI0MiJ9.tydfCeXBICtX_xtgsOEiDJFmVPo6MmaAh1Bojouprjc"
assert request.headers["Authorization"] == f"JWT {raw_jwt}"
@@ -113,7 +113,7 @@ def test_authorize_request(self):
"iat": 1672534861,
"iss": "testserver.jira",
"qsh": get_query_hash(
- uri=self.client.SERVER_INFO_URL, method=method, query_params=params
+ uri=self.jira_client.SERVER_INFO_URL, method=method, query_params=params
),
}
@@ -133,7 +133,7 @@ def assert_proxy_request(self, request, is_proxy=True):
responses.add(
method=responses.GET,
# Use regex to create responses both from proxy and integration
- url=re.compile(rf"\S+{self.client.SERVER_INFO_URL}$"),
+ url=re.compile(rf"\S+{self.jira_client.SERVER_INFO_URL}$"),
json={"ok": True},
status=200,
)
diff --git a/tests/sentry/integrations/jira/test_integration.py b/tests/sentry/integrations/jira/test_integration.py
index 57f668ead0ffbb..aae0d0d9a6cdf0 100644
--- a/tests/sentry/integrations/jira/test_integration.py
+++ b/tests/sentry/integrations/jira/test_integration.py
@@ -8,7 +8,7 @@
from django.test.utils import override_settings
from django.urls import reverse
-from fixtures.integrations.jira import StubJiraApiClient
+from fixtures.integrations.jira.stub_client import StubJiraApiClient
from fixtures.integrations.stub_service import StubService
from sentry.integrations.jira.integration import JiraIntegrationProvider
from sentry.models import (
diff --git a/tests/sentry/integrations/jira/test_webhooks.py b/tests/sentry/integrations/jira/test_webhooks.py
index 49e78f0118719b..dde9f511e2a3a3 100644
--- a/tests/sentry/integrations/jira/test_webhooks.py
+++ b/tests/sentry/integrations/jira/test_webhooks.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from unittest.mock import MagicMock, patch
import responses
@@ -186,7 +188,7 @@ class MockErroringJiraEndpoint(JiraWebhookBase):
# In order to be able to use `as_view`'s `initkwargs` (in other words, in order to be able to
# pass kwargs to `as_view` and have `as_view` pass them onto the `__init__` method below), any
# kwarg we'd like to pass must already be an attibute of the class
- error = None
+ error = BaseException("unreachable")
def __init__(self, error: Exception = dummy_exception, *args, **kwargs):
# We allow the error to be passed in so that we have access to it in the test for use
diff --git a/tests/sentry/integrations/jira_server/__init__.py b/tests/sentry/integrations/jira_server/__init__.py
index bd3d8fbee08868..bd91070b60d8d6 100644
--- a/tests/sentry/integrations/jira_server/__init__.py
+++ b/tests/sentry/integrations/jira_server/__init__.py
@@ -1,3 +1,7 @@
+from __future__ import annotations
+
+from typing import Any
+
from sentry.models import (
ExternalIssue,
Group,
@@ -55,7 +59,7 @@
]
"""
-EXAMPLE_PAYLOAD = {
+EXAMPLE_PAYLOAD: dict[str, Any] = {
"changelog": {
"items": [
{
diff --git a/tests/sentry/integrations/jira_server/test_integration.py b/tests/sentry/integrations/jira_server/test_integration.py
index ac6beeb165396e..a9426cc2ca0a4b 100644
--- a/tests/sentry/integrations/jira_server/test_integration.py
+++ b/tests/sentry/integrations/jira_server/test_integration.py
@@ -7,8 +7,9 @@
import responses
from django.urls import reverse
-from fixtures.integrations.jira import StubJiraApiClient
+from fixtures.integrations.jira.stub_client import StubJiraApiClient
from fixtures.integrations.stub_service import StubService
+from sentry.integrations.jira_server.integration import JiraServerIntegration
from sentry.models import (
ExternalIssue,
GroupLink,
@@ -42,7 +43,9 @@ def setUp(self):
super().setUp()
self.min_ago = iso_format(before_now(minutes=1))
self.integration = get_integration(self.organization, self.user)
- self.installation = self.integration.get_installation(self.organization.id)
+ installation = self.integration.get_installation(self.organization.id)
+ assert isinstance(installation, JiraServerIntegration)
+ self.installation = installation
self.login_as(self.user)
def test_get_create_issue_config(self):
@@ -952,7 +955,9 @@ def setUp(self):
self.plugin.set_option("default_project", "SEN", self.project)
self.plugin.set_option("instance_url", "https://example.atlassian.net", self.project)
self.plugin.set_option("ignored_fields", "hellboy, meow", self.project)
- self.installation = self.integration.get_installation(self.organization.id)
+ installation = self.integration.get_installation(self.organization.id)
+ assert isinstance(installation, JiraServerIntegration)
+ self.installation = installation
self.login_as(self.user)
def test_migrate_plugin(self):
diff --git a/tests/sentry/integrations/msteams/notifications/test_deploy.py b/tests/sentry/integrations/msteams/notifications/test_deploy.py
index 3c7c6080022372..4afc7b1c97ab4c 100644
--- a/tests/sentry/integrations/msteams/notifications/test_deploy.py
+++ b/tests/sentry/integrations/msteams/notifications/test_deploy.py
@@ -4,7 +4,7 @@
from django.utils import timezone
from sentry.models import Activity, Deploy
-from sentry.notifications.notifications.activity import ReleaseActivityNotification
+from sentry.notifications.notifications.activity.release import ReleaseActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest
from sentry.types.activity import ActivityType
@@ -72,6 +72,7 @@ def test_deploy(self, mock_send_card: MagicMock):
== f"http://testserver/organizations/{self.organization.slug}/releases/"
f"{release.version}/?project={project.id}&unselectedSeries=Healthy/"
)
+ assert first_project is not None
assert (
f"{first_project.slug} | [Notification Settings](http://testserver/settings/account/notifications/deploy/?referrer=release\\_activity-msteams-user)"
diff --git a/tests/sentry/integrations/msteams/notifications/test_escalating.py b/tests/sentry/integrations/msteams/notifications/test_escalating.py
index e7db753c6cbe5a..578845182e16fb 100644
--- a/tests/sentry/integrations/msteams/notifications/test_escalating.py
+++ b/tests/sentry/integrations/msteams/notifications/test_escalating.py
@@ -1,7 +1,7 @@
from unittest.mock import MagicMock, Mock, patch
from sentry.models import Activity
-from sentry.notifications.notifications.activity import EscalatingActivityNotification
+from sentry.notifications.notifications.activity.escalating import EscalatingActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest
from sentry.types.activity import ActivityType
diff --git a/tests/sentry/integrations/msteams/notifications/test_note.py b/tests/sentry/integrations/msteams/notifications/test_note.py
index ede9fa76de10e1..6ffafd42693eef 100644
--- a/tests/sentry/integrations/msteams/notifications/test_note.py
+++ b/tests/sentry/integrations/msteams/notifications/test_note.py
@@ -1,7 +1,7 @@
from unittest.mock import MagicMock, Mock, patch
from sentry.models import Activity
-from sentry.notifications.notifications.activity import NoteActivityNotification
+from sentry.notifications.notifications.activity.note import NoteActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest
from sentry.types.activity import ActivityType
diff --git a/tests/sentry/integrations/msteams/notifications/test_regression.py b/tests/sentry/integrations/msteams/notifications/test_regression.py
index 1955705997f65d..00ac13ffb33cc9 100644
--- a/tests/sentry/integrations/msteams/notifications/test_regression.py
+++ b/tests/sentry/integrations/msteams/notifications/test_regression.py
@@ -1,7 +1,7 @@
from unittest.mock import MagicMock, Mock, patch
from sentry.models import Activity
-from sentry.notifications.notifications.activity import RegressionActivityNotification
+from sentry.notifications.notifications.activity.regression import RegressionActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest
from sentry.types.activity import ActivityType
diff --git a/tests/sentry/integrations/msteams/notifications/test_resolved.py b/tests/sentry/integrations/msteams/notifications/test_resolved.py
index 7e0edb462a0913..e381cd3e1a5dd7 100644
--- a/tests/sentry/integrations/msteams/notifications/test_resolved.py
+++ b/tests/sentry/integrations/msteams/notifications/test_resolved.py
@@ -1,8 +1,8 @@
from unittest.mock import MagicMock, Mock, patch
from sentry.models import Activity
-from sentry.notifications.notifications.activity import (
- ResolvedActivityNotification,
+from sentry.notifications.notifications.activity.resolved import ResolvedActivityNotification
+from sentry.notifications.notifications.activity.resolved_in_release import (
ResolvedInReleaseActivityNotification,
)
from sentry.testutils.cases import MSTeamsActivityNotificationTest
diff --git a/tests/sentry/integrations/msteams/notifications/test_unassigned.py b/tests/sentry/integrations/msteams/notifications/test_unassigned.py
index a68a7cc6efacd4..2c0fb90063fdf4 100644
--- a/tests/sentry/integrations/msteams/notifications/test_unassigned.py
+++ b/tests/sentry/integrations/msteams/notifications/test_unassigned.py
@@ -1,7 +1,7 @@
from unittest.mock import MagicMock, Mock, patch
from sentry.models import Activity
-from sentry.notifications.notifications.activity import UnassignedActivityNotification
+from sentry.notifications.notifications.activity.unassigned import UnassignedActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest
from sentry.types.activity import ActivityType
diff --git a/tests/sentry/integrations/msteams/test_action_state_change.py b/tests/sentry/integrations/msteams/test_action_state_change.py
index 23083d7e33bd59..be365caef812c1 100644
--- a/tests/sentry/integrations/msteams/test_action_state_change.py
+++ b/tests/sentry/integrations/msteams/test_action_state_change.py
@@ -67,6 +67,7 @@ def setUp(self):
data={"message": "oh no"},
project_id=self.project1.id,
)
+ assert self.event1.group is not None
self.group1 = self.event1.group
def post_webhook(
diff --git a/tests/sentry/integrations/msteams/test_client.py b/tests/sentry/integrations/msteams/test_client.py
index ca5becf1124c49..41f8c1a3eab9ac 100644
--- a/tests/sentry/integrations/msteams/test_client.py
+++ b/tests/sentry/integrations/msteams/test_client.py
@@ -47,14 +47,14 @@ def setUp(self):
json=access_json,
)
- self.client = MsTeamsClient(self.integration)
+ self.msteams_client = MsTeamsClient(self.integration)
@responses.activate
def test_token_refreshes(self):
with patch("time.time") as mock_time:
mock_time.return_value = self.expires_at
# accessing the property should refresh the token
- self.client.access_token
+ self.msteams_client.access_token
body = responses.calls[0].request.body
assert body == urlencode(
{
@@ -77,7 +77,7 @@ def test_no_token_refresh(self):
with patch("time.time") as mock_time:
mock_time.return_value = self.expires_at - 100
# accessing the property should refresh the token
- self.client.access_token
+ self.msteams_client.access_token
assert not responses.calls
integration = Integration.objects.get(provider="msteams")
@@ -89,7 +89,7 @@ def test_no_token_refresh(self):
@responses.activate
def test_simple(self):
- self.client.get_team_info("foobar")
+ self.msteams_client.get_team_info("foobar")
assert len(responses.calls) == 2
token_request = responses.calls[0].request
@@ -102,7 +102,7 @@ def test_simple(self):
# API request to service url
request = responses.calls[1].request
assert "https://smba.trafficmanager.net/amer/v3/teams/foobar" == request.url
- assert self.client.base_url in request.url
+ assert self.msteams_client.base_url in request.url
# Check if metrics is generated properly
calls = [
diff --git a/tests/sentry/integrations/msteams/test_helpers.py b/tests/sentry/integrations/msteams/test_helpers.py
index 7eed74d3518aea..d73cca9e0b13ed 100644
--- a/tests/sentry/integrations/msteams/test_helpers.py
+++ b/tests/sentry/integrations/msteams/test_helpers.py
@@ -1,10 +1,14 @@
-GENERIC_EVENT = {
+from __future__ import annotations
+
+from typing import Any
+
+GENERIC_EVENT: dict[str, Any] = {
"serviceUrl": "https://smba.trafficmanager.net/amer/",
"channelData": {"eventType": "otherEvent"},
"type": "conversationUpdate",
}
-EXAMPLE_TEAM_MEMBER_ADDED = {
+EXAMPLE_TEAM_MEMBER_ADDED: dict[str, Any] = {
"recipient": {"id": "28:5710acff-f313-453f-8b75-44fff54bab14", "name": "Steve-Bot-5"},
"from": {
"aadObjectId": "a6de2a64-9501-4e16-9e50-74df223570a3",
@@ -33,7 +37,7 @@
"id": "f:8e005ef8-f848-156f-55b1-0a5bb3207225",
}
-EXAMPLE_TEAM_MEMBER_REMOVED = {
+EXAMPLE_TEAM_MEMBER_REMOVED: dict[str, Any] = {
"membersRemoved": [{"id": "28:5710acff-f313-453f-8b75-44fff54bab14"}],
"type": "conversationUpdate",
"timestamp": "2020-07-16T23:47:29.7965243Z",
@@ -62,7 +66,7 @@
},
}
-EXAMPLE_PERSONAL_MEMBER_ADDED = {
+EXAMPLE_PERSONAL_MEMBER_ADDED: dict[str, Any] = {
"recipient": {"id": "28:5710acff-f313-453f-8b75-44fff54bab14", "name": "Steve-Bot-5"},
"from": {
"aadObjectId": "a6de2a64-9501-4e16-9e50-74df223570a3",
@@ -82,7 +86,7 @@
"id": "f:d4414f98-25be-6cc7-b8c7-f01d51e3afd0",
}
-EXAMPLE_UNLINK_COMMAND = {
+EXAMPLE_UNLINK_COMMAND: dict[str, Any] = {
"text": "unlink ",
"recipient": {"id": "28:5710acff-f313-453f-8b75-44fff54bab14", "name": "Steve-Bot-5"},
"from": {
@@ -103,7 +107,7 @@
}
-EXAMPLE_MENTIONED = {
+EXAMPLE_MENTIONED: dict[str, Any] = {
"text": "<at>SentryTest</at> help\n",
"recipient": {"id": "28:5710acff-f313-453f-8b75-44fff54bab14", "name": "Steve-Bot-5"},
"from": {
@@ -153,7 +157,7 @@
"aud": "msteams-client-id",
}
-OPEN_ID_CONFIG = {
+OPEN_ID_CONFIG: dict[str, Any] = {
"issuer": "https://api.botframework.com",
"authorization_endpoint": "https://invalid.botframework.com",
"jwks_uri": "https://login.botframework.com/v1/.well-known/keys",
diff --git a/tests/sentry/integrations/msteams/test_notifications.py b/tests/sentry/integrations/msteams/test_notifications.py
index d3661a489c83f4..aa655ac13c0eae 100644
--- a/tests/sentry/integrations/msteams/test_notifications.py
+++ b/tests/sentry/integrations/msteams/test_notifications.py
@@ -4,7 +4,7 @@
from sentry.integrations.msteams.notifications import send_notification_as_msteams
from sentry.models import Activity
-from sentry.notifications.notifications.activity import NoteActivityNotification
+from sentry.notifications.notifications.activity.note import NoteActivityNotification
from sentry.testutils.cases import MSTeamsActivityNotificationTest, TestCase
from sentry.testutils.helpers.notifications import (
DummyNotification,
diff --git a/tests/sentry/integrations/msteams/test_notify_action.py b/tests/sentry/integrations/msteams/test_notify_action.py
index 40842069dc239b..ed46950a9c8fab 100644
--- a/tests/sentry/integrations/msteams/test_notify_action.py
+++ b/tests/sentry/integrations/msteams/test_notify_action.py
@@ -76,12 +76,12 @@ def test_applies_correctly_generic_issue(self, occurrence):
event = self.store_event(
data={"message": "Hello world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
rule = self.get_rule(
data={"team": self.integration.id, "channel": "Hellboy", "channel_id": "nb"}
)
- results = list(rule.after(event=event, state=self.get_state()))
+ results = list(rule.after(event=group_event, state=self.get_state()))
assert len(results) == 1
responses.add(
diff --git a/tests/sentry/integrations/pagerduty/test_client.py b/tests/sentry/integrations/pagerduty/test_client.py
index 528b867105b58b..b3f74cbc57b51a 100644
--- a/tests/sentry/integrations/pagerduty/test_client.py
+++ b/tests/sentry/integrations/pagerduty/test_client.py
@@ -67,6 +67,7 @@ def test_send_trigger(self):
project_id=self.project.id,
)
custom_details = serialize(event, None, ExternalEventSerializer())
+ assert event.group is not None
group = event.group
expected_data = {
"routing_key": integration_key,
diff --git a/tests/sentry/integrations/pagerduty/test_notify_action.py b/tests/sentry/integrations/pagerduty/test_notify_action.py
index da8edc1e3cc0b5..fe4202504d2614 100644
--- a/tests/sentry/integrations/pagerduty/test_notify_action.py
+++ b/tests/sentry/integrations/pagerduty/test_notify_action.py
@@ -2,7 +2,7 @@
import responses
-from sentry.integrations.pagerduty import PagerDutyNotifyServiceAction
+from sentry.integrations.pagerduty.actions.notification import PagerDutyNotifyServiceAction
from sentry.models import Integration, OrganizationIntegration
from sentry.silo import SiloMode
from sentry.testutils.cases import PerformanceIssueTestCase, RuleTestCase
@@ -116,11 +116,11 @@ def test_applies_correctly_generic_issue(self):
},
project_id=self.project.id,
)
- event = event.for_group(event.groups[0])
- event.occurrence = occurrence
+ group_event = event.for_group(event.groups[0])
+ group_event.occurrence = occurrence
rule = self.get_rule(data={"account": self.integration.id, "service": self.service["id"]})
- results = list(rule.after(event=event, state=self.get_state()))
+ results = list(rule.after(event=group_event, state=self.get_state()))
assert len(results) == 1
responses.add(
@@ -132,12 +132,12 @@ def test_applies_correctly_generic_issue(self):
)
# Trigger rule callback
- results[0].callback(event, futures=[])
+ results[0].callback(group_event, futures=[])
data = json.loads(responses.calls[0].request.body)
assert data["event_action"] == "trigger"
- assert data["payload"]["summary"] == event.occurrence.issue_title
- assert data["payload"]["custom_details"]["title"] == event.occurrence.issue_title
+ assert data["payload"]["summary"] == group_event.occurrence.issue_title
+ assert data["payload"]["custom_details"]["title"] == group_event.occurrence.issue_title
def test_render_label(self):
rule = self.get_rule(data={"account": self.integration.id, "service": self.service["id"]})
diff --git a/tests/sentry/integrations/slack/notifications/test_assigned.py b/tests/sentry/integrations/slack/notifications/test_assigned.py
index 6122b0a98cf58f..ff114009e4c34c 100644
--- a/tests/sentry/integrations/slack/notifications/test_assigned.py
+++ b/tests/sentry/integrations/slack/notifications/test_assigned.py
@@ -4,7 +4,7 @@
import responses
from sentry.models import Activity, Identity, IdentityProvider, IdentityStatus, Integration
-from sentry.notifications.notifications.activity import AssignedActivityNotification
+from sentry.notifications.notifications.activity.assigned import AssignedActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -145,10 +145,10 @@ def test_assignment_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
with self.tasks():
- self.create_notification(event.group, AssignedActivityNotification).send()
+ self.create_notification(group_event.group, AssignedActivityNotification).send()
attachment, text = get_attachment()
assert text == f"Issue assigned to {self.name} by themselves"
self.assert_generic_issue_attachments(
diff --git a/tests/sentry/integrations/slack/notifications/test_deploy.py b/tests/sentry/integrations/slack/notifications/test_deploy.py
index 3837086d3579e3..582b5a312275ba 100644
--- a/tests/sentry/integrations/slack/notifications/test_deploy.py
+++ b/tests/sentry/integrations/slack/notifications/test_deploy.py
@@ -4,7 +4,7 @@
from django.utils import timezone
from sentry.models import Activity, Deploy, Release
-from sentry.notifications.notifications.activity import ReleaseActivityNotification
+from sentry.notifications.notifications.activity.release import ReleaseActivityNotification
from sentry.testutils.cases import SlackActivityNotificationTest
from sentry.testutils.helpers.slack import get_attachment, send_notification
from sentry.testutils.silo import region_silo_test
@@ -65,6 +65,7 @@ def test_deploy(self, mock_func):
== f"http://testserver/organizations/{self.organization.slug}/releases/"
f"{release.version}/?project={project.id}&unselectedSeries=Healthy/"
)
+ assert first_project is not None
assert (
attachment["footer"]
diff --git a/tests/sentry/integrations/slack/notifications/test_escalating.py b/tests/sentry/integrations/slack/notifications/test_escalating.py
index b7ce2005e9d260..4fc7c11848f0f6 100644
--- a/tests/sentry/integrations/slack/notifications/test_escalating.py
+++ b/tests/sentry/integrations/slack/notifications/test_escalating.py
@@ -3,7 +3,7 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import EscalatingActivityNotification
+from sentry.notifications.notifications.activity.escalating import EscalatingActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -88,17 +88,17 @@ def test_escalating_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
with self.tasks():
- self.create_notification(event.group).send()
+ self.create_notification(group_event.group).send()
attachment, text = get_attachment()
assert text == "Issue marked as escalating"
assert attachment["title"] == TEST_ISSUE_OCCURRENCE.issue_title
assert (
attachment["title_link"]
- == f"http://testserver/organizations/{self.organization.slug}/issues/{event.group.id}/?referrer=escalating_activity-slack"
+ == f"http://testserver/organizations/{self.organization.slug}/issues/{group_event.group.id}/?referrer=escalating_activity-slack"
)
assert (
attachment["text"]
diff --git a/tests/sentry/integrations/slack/notifications/test_issue_alert.py b/tests/sentry/integrations/slack/notifications/test_issue_alert.py
index e72254a3cdd2fc..736383f85ef601 100644
--- a/tests/sentry/integrations/slack/notifications/test_issue_alert.py
+++ b/tests/sentry/integrations/slack/notifications/test_issue_alert.py
@@ -114,10 +114,10 @@ def test_generic_issue_alert_user(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
notification = AlertRuleNotification(
- Notification(event=event, rule=self.rule), ActionTargetType.MEMBER, self.user.id
+ Notification(event=group_event, rule=self.rule), ActionTargetType.MEMBER, self.user.id
)
with self.tasks():
notification.send()
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 192f3be3e9e4c5..d429240e4c2901 100644
--- a/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py
+++ b/tests/sentry/integrations/slack/notifications/test_new_processing_issues.py
@@ -3,7 +3,9 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import NewProcessingIssuesActivityNotification
+from sentry.notifications.notifications.activity.new_processing_issues import (
+ NewProcessingIssuesActivityNotification,
+)
from sentry.testutils.cases import SlackActivityNotificationTest
from sentry.testutils.helpers.features import with_feature
from sentry.testutils.helpers.slack import get_attachment, send_notification
diff --git a/tests/sentry/integrations/slack/notifications/test_note.py b/tests/sentry/integrations/slack/notifications/test_note.py
index d9a2c6888e3415..4812f67ac42253 100644
--- a/tests/sentry/integrations/slack/notifications/test_note.py
+++ b/tests/sentry/integrations/slack/notifications/test_note.py
@@ -3,7 +3,7 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import NoteActivityNotification
+from sentry.notifications.notifications.activity.note import NoteActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -85,8 +85,8 @@ def test_note_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
- notification = self.create_notification(event.group)
+ group_event = event.for_group(event.groups[0])
+ notification = self.create_notification(group_event.group)
with self.tasks():
notification.send()
diff --git a/tests/sentry/integrations/slack/notifications/test_regression.py b/tests/sentry/integrations/slack/notifications/test_regression.py
index 95ddc91e41be30..54720e49ba87dd 100644
--- a/tests/sentry/integrations/slack/notifications/test_regression.py
+++ b/tests/sentry/integrations/slack/notifications/test_regression.py
@@ -3,7 +3,7 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import RegressionActivityNotification
+from sentry.notifications.notifications.activity.regression import RegressionActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -96,10 +96,10 @@ def test_regression_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
with self.tasks():
- self.create_notification(event.group).send()
+ self.create_notification(group_event.group).send()
attachment, text = get_attachment()
assert text == "Issue marked as regression"
diff --git a/tests/sentry/integrations/slack/notifications/test_resolved.py b/tests/sentry/integrations/slack/notifications/test_resolved.py
index def5f9371a55be..a9078e61890f99 100644
--- a/tests/sentry/integrations/slack/notifications/test_resolved.py
+++ b/tests/sentry/integrations/slack/notifications/test_resolved.py
@@ -3,7 +3,7 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import ResolvedActivityNotification
+from sentry.notifications.notifications.activity.resolved import ResolvedActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -79,14 +79,14 @@ def test_resolved_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
with self.tasks():
- self.create_notification(event.group).send()
+ self.create_notification(group_event.group).send()
attachment, text = get_attachment()
assert (
text
- == f"{self.name} marked <http://testserver/organizations/{self.organization.slug}/issues/{event.group.id}/?referrer=activity_notification|{self.project.slug.upper()}-{event.group.short_id}> as resolved"
+ == f"{self.name} marked <http://testserver/organizations/{self.organization.slug}/issues/{group_event.group.id}/?referrer=activity_notification|{self.project.slug.upper()}-{group_event.group.short_id}> as resolved"
)
self.assert_generic_issue_attachments(
attachment, self.project.slug, "resolved_activity-slack-user"
diff --git a/tests/sentry/integrations/slack/notifications/test_resolved_in_release.py b/tests/sentry/integrations/slack/notifications/test_resolved_in_release.py
index e0dbfa7a50654a..e3aaa1acf13274 100644
--- a/tests/sentry/integrations/slack/notifications/test_resolved_in_release.py
+++ b/tests/sentry/integrations/slack/notifications/test_resolved_in_release.py
@@ -3,7 +3,9 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import ResolvedInReleaseActivityNotification
+from sentry.notifications.notifications.activity.resolved_in_release import (
+ ResolvedInReleaseActivityNotification,
+)
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -81,8 +83,8 @@ def test_resolved_in_release_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
- notification = self.create_notification(event.group)
+ group_event = event.for_group(event.groups[0])
+ notification = self.create_notification(group_event.group)
with self.tasks():
notification.send()
diff --git a/tests/sentry/integrations/slack/notifications/test_unassigned.py b/tests/sentry/integrations/slack/notifications/test_unassigned.py
index 4b1d6189ac8602..5ac0edf5796599 100644
--- a/tests/sentry/integrations/slack/notifications/test_unassigned.py
+++ b/tests/sentry/integrations/slack/notifications/test_unassigned.py
@@ -3,7 +3,7 @@
import responses
from sentry.models import Activity
-from sentry.notifications.notifications.activity import UnassignedActivityNotification
+from sentry.notifications.notifications.activity.unassigned import UnassignedActivityNotification
from sentry.testutils.cases import PerformanceIssueTestCase, SlackActivityNotificationTest
from sentry.testutils.helpers.notifications import TEST_ISSUE_OCCURRENCE, TEST_PERF_ISSUE_OCCURRENCE
from sentry.testutils.helpers.slack import get_attachment, send_notification
@@ -74,9 +74,9 @@ def test_unassignment_generic_issue(self, mock_func, occurrence):
event = self.store_event(
data={"message": "Hellboy's world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
with self.tasks():
- self.create_notification(event.group).send()
+ self.create_notification(group_event.group).send()
attachment, text = get_attachment()
assert text == f"Issue unassigned by {self.name}"
diff --git a/tests/sentry/integrations/slack/test_client.py b/tests/sentry/integrations/slack/test_client.py
index f06b310da0cdf3..271afd6905f37f 100644
--- a/tests/sentry/integrations/slack/test_client.py
+++ b/tests/sentry/integrations/slack/test_client.py
@@ -35,14 +35,18 @@ def setUp(self):
self.mock_user_access_token_response = {"ok": True, "auth": "user"}
self.mock_access_token_response = {"ok": True, "auth": "token"}
self.mock_not_authed_response = {"ok": True, "auth": None}
- base_response_kwargs = {
- "method": responses.POST,
- "url": re.compile(r"\S+chat.postMessage$"),
- "status": 200,
- "content_type": "application/json",
- }
- responses.add(
- **base_response_kwargs,
+
+ def _add_response(*, json, match):
+ responses.add(
+ method=responses.POST,
+ url=re.compile(r"\S+chat.postMessage$"),
+ status=200,
+ content_type="application/json",
+ json=json,
+ match=match,
+ )
+
+ _add_response(
json=self.mock_user_access_token_response,
match=[
matchers.header_matcher(
@@ -50,13 +54,11 @@ def setUp(self):
)
],
)
- responses.add(
- **base_response_kwargs,
+ _add_response(
json=self.mock_access_token_response,
match=[matchers.header_matcher({"Authorization": f"Bearer {self.access_token}"})],
)
- responses.add(
- **base_response_kwargs,
+ _add_response(
json=self.mock_not_authed_response,
match=[matchers.header_matcher({})],
)
diff --git a/tests/sentry/integrations/slack/test_integration.py b/tests/sentry/integrations/slack/test_integration.py
index baa9d116e10e8f..4ebc64e8c03a14 100644
--- a/tests/sentry/integrations/slack/test_integration.py
+++ b/tests/sentry/integrations/slack/test_integration.py
@@ -361,12 +361,12 @@ def setUp(self):
self.installation = SlackIntegration(self.integration, self.organization.id)
def test_config_data_workspace_app(self):
- self.installation.get_config_data()["installationType"] = "workspace_app"
+ assert self.installation.get_config_data()["installationType"] == "workspace_app"
def test_config_data_user_token(self):
self.integration.metadata["user_access_token"] = "token"
- self.installation.get_config_data()["installationType"] = "classic_bot"
+ assert self.installation.get_config_data()["installationType"] == "classic_bot"
def test_config_data_born_as_bot(self):
self.integration.metadata["installation_type"] = "born_as_bot"
- self.installation.get_config_data()["installationType"] = "born_as_bot"
+ assert self.installation.get_config_data()["installationType"] == "born_as_bot"
diff --git a/tests/sentry/integrations/slack/test_message_builder.py b/tests/sentry/integrations/slack/test_message_builder.py
index 6bf0cb733d04be..f6938e8bf15263 100644
--- a/tests/sentry/integrations/slack/test_message_builder.py
+++ b/tests/sentry/integrations/slack/test_message_builder.py
@@ -1,7 +1,7 @@
from __future__ import annotations
from datetime import datetime
-from typing import Any, Mapping
+from typing import Any
from unittest.mock import patch
from django.urls import reverse
@@ -34,7 +34,7 @@ def build_test_message(
group: Group,
event: Event | None = None,
link_to_event: bool = False,
-) -> Mapping[str, Any]:
+) -> dict[str, Any]:
project = group.project
title = group.title
@@ -102,7 +102,9 @@ def test_build_group_attachment(self):
event = self.store_event(data={}, project_id=self.project.id)
- assert SlackIssuesMessageBuilder(group, event).build() == build_test_message(
+ assert SlackIssuesMessageBuilder(
+ group, event.for_group(group)
+ ).build() == build_test_message(
teams={self.team},
users={self.user},
timestamp=event.datetime,
@@ -111,7 +113,7 @@ def test_build_group_attachment(self):
)
assert SlackIssuesMessageBuilder(
- group, event, link_to_event=True
+ group, event.for_group(group), link_to_event=True
).build() == build_test_message(
teams={self.team},
users={self.user},
@@ -161,52 +163,60 @@ def test_build_group_attachment_prune_duplicate_assignees(self, mock_get_option_
def test_build_group_attachment_issue_alert(self):
issue_alert_group = self.create_group(project=self.project)
- assert (
- SlackIssuesMessageBuilder(issue_alert_group, issue_details=True).build()["actions"]
- == []
- )
+ ret = SlackIssuesMessageBuilder(issue_alert_group, issue_details=True).build()
+ assert isinstance(ret, dict)
+ assert ret["actions"] == []
def test_team_recipient(self):
issue_alert_group = self.create_group(project=self.project)
- assert (
- SlackIssuesMessageBuilder(
- issue_alert_group, recipient=RpcActor.from_object(self.team)
- ).build()["actions"]
- != []
- )
+ ret = SlackIssuesMessageBuilder(
+ issue_alert_group, recipient=RpcActor.from_object(self.team)
+ ).build()
+ assert isinstance(ret, dict)
+ assert ret["actions"] != []
def test_build_group_attachment_color_no_event_error_fallback(self):
group_with_no_events = self.create_group(project=self.project)
- assert SlackIssuesMessageBuilder(group_with_no_events).build()["color"] == "#E03E2F"
+ ret = SlackIssuesMessageBuilder(group_with_no_events).build()
+ assert isinstance(ret, dict)
+ assert ret["color"] == "#E03E2F"
def test_build_group_attachment_color_unexpected_level_error_fallback(self):
unexpected_level_event = self.store_event(
data={"level": "trace"}, project_id=self.project.id, assert_no_errors=False
)
- assert SlackIssuesMessageBuilder(unexpected_level_event.group).build()["color"] == "#E03E2F"
+ assert unexpected_level_event.group is not None
+ ret = SlackIssuesMessageBuilder(unexpected_level_event.group).build()
+ assert isinstance(ret, dict)
+ assert ret["color"] == "#E03E2F"
def test_build_group_attachment_color_warning(self):
warning_event = self.store_event(data={"level": "warning"}, project_id=self.project.id)
- assert SlackIssuesMessageBuilder(warning_event.group).build()["color"] == "#FFC227"
- assert (
- SlackIssuesMessageBuilder(warning_event.group, warning_event).build()["color"]
- == "#FFC227"
- )
+ assert warning_event.group is not None
+ ret1 = SlackIssuesMessageBuilder(warning_event.group).build()
+ assert isinstance(ret1, dict)
+ assert ret1["color"] == "#FFC227"
+ ret2 = SlackIssuesMessageBuilder(
+ warning_event.group, warning_event.for_group(warning_event.group)
+ ).build()
+ assert isinstance(ret2, dict)
+ assert ret2["color"] == "#FFC227"
def test_build_group_generic_issue_attachment(self):
"""Test that a generic issue type's Slack alert contains the expected values"""
event = self.store_event(
data={"message": "Hello world", "level": "error"}, project_id=self.project.id
)
- event = event.for_group(event.groups[0])
+ group_event = event.for_group(event.groups[0])
occurrence = self.build_occurrence(level="info")
occurrence.save()
- event.occurrence = occurrence
+ group_event.occurrence = occurrence
- event.group.type = ProfileFileIOGroupType.type_id
+ group_event.group.type = ProfileFileIOGroupType.type_id
- attachments = SlackIssuesMessageBuilder(group=event.group, event=event).build()
+ attachments = SlackIssuesMessageBuilder(group=group_event.group, event=group_event).build()
+ assert isinstance(attachments, dict)
assert attachments["title"] == occurrence.issue_title
assert attachments["text"] == occurrence.evidence_display[0].value
assert attachments["fallback"] == f"[{self.project.slug}] {occurrence.issue_title}"
@@ -214,13 +224,16 @@ def test_build_group_generic_issue_attachment(self):
def test_build_error_issue_fallback_text(self):
event = self.store_event(data={}, project_id=self.project.id)
- attachments = SlackIssuesMessageBuilder(event.group, event).build()
+ assert event.group is not None
+ attachments = SlackIssuesMessageBuilder(event.group, event.for_group(event.group)).build()
+ assert isinstance(attachments, dict)
assert attachments["fallback"] == f"[{self.project.slug}] {event.group.title}"
def test_build_performance_issue(self):
event = self.create_performance_issue()
with self.feature("organizations:performance-issues"):
attachments = SlackIssuesMessageBuilder(event.group, event).build()
+ assert isinstance(attachments, dict)
assert attachments["title"] == "N+1 Query"
assert (
attachments["text"]
@@ -237,6 +250,7 @@ def test_build_performance_issue_color_no_event_passed(self):
perf_group = self.create_group(type=PerformanceNPlusOneGroupType.type_id)
attachments = SlackIssuesMessageBuilder(perf_group).build()
+ assert isinstance(attachments, dict)
assert attachments["color"] == "#2788CE" # blue for info level
def test_escape_slack_message(self):
@@ -244,10 +258,9 @@ def test_escape_slack_message(self):
project=self.project,
data={"type": "error", "metadata": {"value": "<https://example.com/|*Click Here*>"}},
)
- assert (
- SlackIssuesMessageBuilder(group, None).build()["text"]
- == "<https://example.com/|*Click Here*>"
- )
+ ret = SlackIssuesMessageBuilder(group, None).build()
+ assert isinstance(ret, dict)
+ assert ret["text"] == "<https://example.com/|*Click Here*>"
class BuildGroupAttachmentReplaysTest(TestCase):
@@ -266,11 +279,15 @@ def test_build_replay_issue(self, has_replays):
},
project_id=self.project.id,
)
+ assert event.group is not None
with self.feature(
["organizations:session-replay", "organizations:session-replay-slack-new-issue"]
):
- attachments = SlackIssuesMessageBuilder(event.group, event).build()
+ attachments = SlackIssuesMessageBuilder(
+ event.group, event.for_group(event.group)
+ ).build()
+ assert isinstance(attachments, dict)
assert (
attachments["text"]
== f"\n\n<http://testserver/organizations/baz/issues/{event.group.id}/replays/?referrer=slack|View Replays>"
diff --git a/tests/sentry/integrations/slack/test_notifications.py b/tests/sentry/integrations/slack/test_notifications.py
index 5d8223950e1eb5..9594532af8dbe9 100644
--- a/tests/sentry/integrations/slack/test_notifications.py
+++ b/tests/sentry/integrations/slack/test_notifications.py
@@ -1,3 +1,4 @@
+from unittest import mock
from urllib.parse import parse_qs
import responses
@@ -18,30 +19,30 @@ def additional_attachment_generator(integration, organization):
@region_silo_test(stable=True)
class SlackNotificationsTest(SlackActivityNotificationTest):
- def tearDown(self):
- manager.attachment_generators[ExternalProviders.SLACK] = None
-
def setUp(self):
super().setUp()
self.notification = DummyNotification(self.organization)
@responses.activate
def test_additional_attachment(self):
- manager.attachment_generators[ExternalProviders.SLACK] = additional_attachment_generator
- with self.tasks():
- send_notification_as_slack(self.notification, [self.user], {}, {})
+ with mock.patch.dict(
+ manager.attachment_generators,
+ {ExternalProviders.SLACK: additional_attachment_generator},
+ ):
+ with self.tasks():
+ send_notification_as_slack(self.notification, [self.user], {}, {})
- data = parse_qs(responses.calls[0].request.body)
+ data = parse_qs(responses.calls[0].request.body)
- assert "attachments" in data
- assert data["text"][0] == "Notification Title"
+ assert "attachments" in data
+ assert data["text"][0] == "Notification Title"
- attachments = json.loads(data["attachments"][0])
- assert len(attachments) == 2
+ attachments = json.loads(data["attachments"][0])
+ assert len(attachments) == 2
- assert attachments[0]["title"] == "My Title"
- assert attachments[1]["title"] == self.organization.slug
- assert attachments[1]["text"] == self.integration.id
+ assert attachments[0]["title"] == "My Title"
+ assert attachments[1]["title"] == self.organization.slug
+ assert attachments[1]["text"] == self.integration.id
@responses.activate
def test_no_additional_attachment(self):
diff --git a/tests/sentry/integrations/slack/test_notify_action.py b/tests/sentry/integrations/slack/test_notify_action.py
index c455040431bfdf..6a8d2d98ef495c 100644
--- a/tests/sentry/integrations/slack/test_notify_action.py
+++ b/tests/sentry/integrations/slack/test_notify_action.py
@@ -1,3 +1,4 @@
+from unittest import mock
from urllib.parse import parse_qs
import responses
@@ -24,9 +25,6 @@ class SlackNotifyActionTest(RuleTestCase):
def setUp(self):
self.integration = install_slack(self.get_event().project.organization)
- def tearDown(self):
- manager.attachment_generators[ExternalProviders.SLACK] = None
-
def assert_form_valid(self, form, expected_channel_id, expected_channel):
assert form.is_valid()
assert form.cleaned_data["channel_id"] == expected_channel_id
@@ -351,33 +349,36 @@ def test_disabled_org_integration(self):
@responses.activate
def test_additional_attachment(self):
- manager.attachment_generators[ExternalProviders.SLACK] = additional_attachment_generator
- event = self.get_event()
-
- rule = self.get_rule(data={"workspace": self.integration.id, "channel": "#my-channel"})
-
- results = list(rule.after(event=event, state=self.get_state()))
- assert len(results) == 1
-
- responses.add(
- method=responses.POST,
- url="https://slack.com/api/chat.postMessage",
- body='{"ok": true}',
- status=200,
- content_type="application/json",
- )
-
- # Trigger rule callback
- results[0].callback(event, futures=[])
- data = parse_qs(responses.calls[0].request.body)
-
- assert "attachments" in data
- attachments = json.loads(data["attachments"][0])
-
- assert len(attachments) == 2
- assert attachments[0]["title"] == event.title
- assert attachments[1]["title"] == self.organization.slug
- assert attachments[1]["text"] == self.integration.id
+ with mock.patch.dict(
+ manager.attachment_generators,
+ {ExternalProviders.SLACK: additional_attachment_generator},
+ ):
+ event = self.get_event()
+
+ rule = self.get_rule(data={"workspace": self.integration.id, "channel": "#my-channel"})
+
+ results = list(rule.after(event=event, state=self.get_state()))
+ assert len(results) == 1
+
+ responses.add(
+ method=responses.POST,
+ url="https://slack.com/api/chat.postMessage",
+ body='{"ok": true}',
+ status=200,
+ content_type="application/json",
+ )
+
+ # Trigger rule callback
+ results[0].callback(event, futures=[])
+ data = parse_qs(responses.calls[0].request.body)
+
+ assert "attachments" in data
+ attachments = json.loads(data["attachments"][0])
+
+ assert len(attachments) == 2
+ assert attachments[0]["title"] == event.title
+ assert attachments[1]["title"] == self.organization.slug
+ assert attachments[1]["text"] == self.integration.id
@responses.activate
def test_multiple_integrations(self):
diff --git a/tests/sentry/integrations/slack/test_unfurl.py b/tests/sentry/integrations/slack/test_unfurl.py
index 9b237f54202ddb..796d3f742090c2 100644
--- a/tests/sentry/integrations/slack/test_unfurl.py
+++ b/tests/sentry/integrations/slack/test_unfurl.py
@@ -189,6 +189,7 @@ def test_unfurl_issues(self):
event = self.store_event(
data={"fingerprint": ["group2"], "timestamp": min_ago}, project_id=self.project.id
)
+ assert event.group is not None
group2 = event.group
links = [
@@ -207,7 +208,9 @@ def test_unfurl_issues(self):
assert unfurls[links[0].url] == SlackIssuesMessageBuilder(self.group).build()
assert (
unfurls[links[1].url]
- == SlackIssuesMessageBuilder(group2, event, link_to_event=True).build()
+ == SlackIssuesMessageBuilder(
+ group2, next(iter(event.build_group_events())), link_to_event=True
+ ).build()
)
def test_escape_issue(self):
diff --git a/tests/sentry/integrations/slack/test_uninstall.py b/tests/sentry/integrations/slack/test_uninstall.py
index 9cddb0476349c5..76769fe6f0bbd4 100644
--- a/tests/sentry/integrations/slack/test_uninstall.py
+++ b/tests/sentry/integrations/slack/test_uninstall.py
@@ -9,7 +9,7 @@
ScheduledDeletion,
User,
)
-from sentry.notifications.helpers import NOTIFICATION_SETTING_DEFAULTS
+from sentry.notifications.defaults import NOTIFICATION_SETTING_DEFAULTS
from sentry.notifications.types import NotificationSettingOptionValues, NotificationSettingTypes
from sentry.testutils.cases import APITestCase
from sentry.testutils.silo import control_silo_test
|
0c3c71bacfa450f7860fb9de211188f9c4bc65d1
|
2022-06-22 23:41:45
|
Gilbert Szeto
|
fix(release-notifications): retrieve the release version from event instead of group (#35900)
| false
|
retrieve the release version from event instead of group (#35900)
|
fix
|
diff --git a/src/sentry/rules/conditions/active_release.py b/src/sentry/rules/conditions/active_release.py
index 89a0a1bfffb6d1..896af924a59bfe 100644
--- a/src/sentry/rules/conditions/active_release.py
+++ b/src/sentry/rules/conditions/active_release.py
@@ -14,6 +14,7 @@
)
from sentry.rules import EventState
from sentry.rules.conditions.base import EventCondition
+from sentry.search.utils import get_latest_release
class ActiveReleaseEventCondition(EventCondition):
@@ -30,12 +31,31 @@ def is_in_active_release(self, event: Event) -> bool:
if not event.group or not event.project:
return False
- last_release_version: Optional[str] = event.group.get_last_release()
- if not last_release_version:
+ # XXX(gilbert):
+ # adapted from LatestReleaseFilter
+ # need to add caching later on
+ environment_id = None if self.rule is None else self.rule.environment_id
+ organization_id = event.group.project.organization_id
+ environments = None
+ if environment_id:
+ environments = [Environment.objects.get(id=environment_id)]
+
+ try:
+ latest_release_versions = get_latest_release(
+ [event.group.project],
+ environments,
+ organization_id,
+ )
+ except Release.DoesNotExist:
return False
- last_release: Release = Release.get(project=event.project, version=last_release_version)
- if not last_release:
+ latest_releases = list(
+ Release.objects.filter(
+ version=latest_release_versions[0], organization_id=organization_id
+ )
+ )
+
+ if not latest_releases:
return False
def release_deploy_time(
@@ -52,7 +72,7 @@ def release_deploy_time(
return release.date_released
else:
if env:
- release_env_project = ReleaseProjectEnvironment.objects.filter(
+ release_project_env = ReleaseProjectEnvironment.objects.filter(
release_id=release.id, project=release.project_id, environment_id=env.id
).first()
@@ -60,21 +80,22 @@ def release_deploy_time(
release_id=release.id, environment_id=env.id
).first()
- if release_env_project and release_env_project.first_seen:
- return release_env_project.first_seen
+ if release_project_env and release_project_env.first_seen:
+ return release_project_env.first_seen
if release_env and release_env.first_seen:
return release_env.first_seen
+
return None
- deploy_time = release_deploy_time(last_release, event.get_environment())
+ deploy_time = release_deploy_time(latest_releases[0], environments)
if deploy_time:
- return bool(now_minus_1_hour.timestamp() <= deploy_time <= now)
+ return bool(now_minus_1_hour <= deploy_time <= now)
return False
def passes(self, event: Event, state: EventState) -> bool:
- if self.rule.environment_id is None: # type: ignore
+ if self.rule and self.rule.environment_id is None:
return (state.is_new or state.is_regression) and self.is_in_active_release(event)
else:
return (
diff --git a/tests/sentry/rules/conditions/test_active_release_event.py b/tests/sentry/rules/conditions/test_active_release_event.py
index 9d33ffc2224468..799d751d2593c1 100644
--- a/tests/sentry/rules/conditions/test_active_release_event.py
+++ b/tests/sentry/rules/conditions/test_active_release_event.py
@@ -1,6 +1,10 @@
+from datetime import datetime, timedelta
+
+from django.utils import timezone
+
from sentry.eventstore import Filter
from sentry.eventstore.snuba import SnubaEventStorage
-from sentry.models import Group, Rule
+from sentry.models import Group, Release, Rule
from sentry.rules.conditions.active_release import ActiveReleaseEventCondition
from sentry.testutils import RuleTestCase, SnubaTestCase
@@ -13,16 +17,62 @@ def setUp(self):
self.eventstore = SnubaEventStorage()
def test_applies_correctly(self):
- rule = self.get_rule(rule=Rule(environment_id=1))
+ rule = self.get_rule()
self.assertDoesNotPass(rule, self.event, is_new=True)
+ def test_release_date_released(self):
+ event = self.get_event()
+ oldRelease = Release.objects.create(
+ organization_id=self.organization.id,
+ version="1",
+ date_added=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ date_released=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ )
+ oldRelease.add_project(self.project)
+
+ newRelease = Release.objects.create(
+ organization_id=self.organization.id,
+ version="2",
+ date_added=timezone.now() - timedelta(minutes=30),
+ date_released=timezone.now() - timedelta(minutes=30),
+ )
+ newRelease.add_project(self.project)
+
+ event.data["tags"] = (("release", newRelease.version),)
+ rule = self.get_rule()
+ self.assertPasses(rule, event)
+
+ def test_deployed(self):
+ pass
+
+ def test_release_project_env(self):
+ pass
+
+ def test_release_env(self):
+ pass
+
# XXX(gilbert): delete this later
def test_event_group_last_release_version(self):
+ oldRelease = Release.objects.create(
+ organization_id=self.organization.id,
+ version="1",
+ date_added=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ )
+ oldRelease.add_project(self.project)
+
+ newRelease = Release.objects.create(
+ organization_id=self.organization.id,
+ version="2",
+ date_added=datetime(2020, 9, 1, 3, 8, 24, 880386),
+ )
+ newRelease.add_project(self.project)
+
evt = self.store_event(
data={
"event_id": "a" * 32,
"message": "\u3053\u3093\u306b\u3061\u306f",
+ "tags": (("release", newRelease.version),),
},
project_id=self.project.id,
)
@@ -30,6 +80,7 @@ def test_event_group_last_release_version(self):
data={
"event_id": "b" * 32,
"message": "\u3053\u3093\u306b\u3061\u306f",
+ "tags": (("release", newRelease.version),),
},
project_id=self.project.id,
)
@@ -48,6 +99,9 @@ def test_event_group_last_release_version(self):
Group.objects.filter(id__in=(evt.group_id, evt2.group_id)).values_list("id", flat=True)
) == [evt.group_id]
- rule = self.get_rule(rule=Rule(environment_id=1))
+ # assert GroupRelease.objects.all().count() == 1
+ rule = self.get_rule(rule=Rule(environment_id=self.environment.id))
+
+ self.assertDoesNotPass(rule, evt)
- self.assertDoesNotPass(rule, evt, is_new=True)
+ # self.assertDoesNotPass(rule, evt, is_new=True)
|
94a0ebc2f724861a7feb4d55354837fc6d2596b7
|
2021-10-12 23:43:48
|
Evan Purkhiser
|
ref(js): Convert ActivityNote to a functional component (#29250)
| false
|
Convert ActivityNote to a functional component (#29250)
|
ref
|
diff --git a/static/app/components/activity/note/index.tsx b/static/app/components/activity/note/index.tsx
index 29f5e3a6e39be8..5e62665259c63e 100644
--- a/static/app/components/activity/note/index.tsx
+++ b/static/app/components/activity/note/index.tsx
@@ -1,4 +1,4 @@
-import {Component} from 'react';
+import {useState} from 'react';
import styled from '@emotion/styled';
import ActivityItem, {ActivityAuthorType} from 'app/components/activity/item';
@@ -14,13 +14,15 @@ import NoteInput from './input';
type Props = {
/**
- * String for author name to be displayed in header
- * This is not completely derived from `props.user` because we can set a default from parent component
+ * String for author name to be displayed in header.
+ *
+ * This is not completely derived from `props.user` because we can set a
+ * default from parent component
*/
authorName: string;
/**
- * This is the id of the note object from the server
- * This is to indicate you are editing an existing item
+ * This is the id of the note object from the server. This is to indicate you
+ * are editing an existing item
*/
modelId: string;
/**
@@ -30,8 +32,8 @@ type Props = {
user: User;
dateCreated: Date | string;
/**
- * pass through to ActivityItem
- * shows absolute time instead of a relative string
+ * Pass through to ActivityItem. Shows absolute time instead of a relative
+ * string
*/
showTime: boolean;
/**
@@ -46,119 +48,82 @@ type Props = {
onDelete: (props: Props) => void;
onCreate?: (data: NoteType) => void;
/**
- * This is unusual usage that Alert Details uses to get
- * back the activity that an input was bound to as the onUpdate and onDelete
- * actions forward this component's props.
+ * This is unusual usage that Alert Details uses to get back the activity
+ * that an input was bound to as the onUpdate and onDelete actions forward
+ * this component's props.
*/
activity?: ActivityType;
/**
- * pass through to ActivityItem
- * hides the date/timestamp in header
+ * pass through to ActivityItem. Hides the date/timestamp in header
*/
hideDate?: boolean;
};
-type State = {
- editing: boolean;
-};
-
-class Note extends Component<Props, State> {
- state: State = {
- editing: false,
- };
-
- handleEdit = () => {
- this.setState({editing: true});
- };
-
- handleEditFinish = () => {
- this.setState({editing: false});
- };
-
- handleDelete = () => {
- const {onDelete} = this.props;
-
- onDelete(this.props);
- };
-
- handleCreate = (note: NoteType) => {
- const {onCreate} = this.props;
-
- if (onCreate) {
- onCreate(note);
- }
- };
-
- handleUpdate = (note: NoteType) => {
- const {onUpdate} = this.props;
-
- onUpdate(note, this.props);
- this.setState({editing: false});
+function Note(props: Props) {
+ const [editing, setEditing] = useState(false);
+
+ const {
+ modelId,
+ user,
+ dateCreated,
+ text,
+ authorName,
+ hideDate,
+ minHeight,
+ showTime,
+ projectSlugs,
+ onDelete,
+ onCreate,
+ onUpdate,
+ } = props;
+
+ const activityItemProps = {
+ hideDate,
+ showTime,
+ id: `activity-item-${modelId}`,
+ author: {
+ type: 'user' as ActivityAuthorType,
+ user,
+ },
+ date: dateCreated,
};
- render() {
- const {
- modelId,
- user,
- dateCreated,
- text,
- authorName,
- hideDate,
- minHeight,
- showTime,
- projectSlugs,
- } = this.props;
-
- const activityItemProps = {
- hideDate,
- showTime,
- id: `activity-item-${modelId}`,
- author: {
- type: 'user' as ActivityAuthorType,
- user,
- },
- date: dateCreated,
- };
-
- if (!this.state.editing) {
- return (
- <ActivityItemWithEditing
- {...activityItemProps}
- header={
- <NoteHeader
- authorName={authorName}
- user={user}
- onEdit={this.handleEdit}
- onDelete={this.handleDelete}
- />
- }
- >
- <NoteBody text={text} />
- </ActivityItemWithEditing>
- );
- }
+ if (!editing) {
+ const header = (
+ <NoteHeader
+ {...{authorName, user}}
+ onEdit={() => setEditing(true)}
+ onDelete={() => onDelete(props)}
+ />
+ );
- // When editing, `NoteInput` has its own header, pass render func
- // to control rendering of bubble body
return (
- <StyledActivityItem {...activityItemProps}>
- {() => (
- <NoteInput
- modelId={modelId}
- minHeight={minHeight}
- text={text}
- onEditFinish={this.handleEditFinish}
- onUpdate={this.handleUpdate}
- onCreate={this.handleCreate}
- projectSlugs={projectSlugs}
- />
- )}
- </StyledActivityItem>
+ <ActivityItemWithEditing {...activityItemProps} header={header}>
+ <NoteBody text={text} />
+ </ActivityItemWithEditing>
);
}
+
+ // When editing, `NoteInput` has its own header, pass render func to control
+ // rendering of bubble body
+ return (
+ <ActivityItemNote {...activityItemProps}>
+ {() => (
+ <NoteInput
+ {...{modelId, minHeight, text, projectSlugs}}
+ onEditFinish={() => setEditing(false)}
+ onUpdate={note => {
+ onUpdate(note, props);
+ setEditing(false);
+ }}
+ onCreate={note => onCreate?.(note)}
+ />
+ )}
+ </ActivityItemNote>
+ );
}
-const StyledActivityItem = styled(ActivityItem)`
+const ActivityItemNote = styled(ActivityItem)`
/* this was nested under ".activity-note.activity-bubble" */
ul {
list-style: disc;
@@ -196,7 +161,7 @@ const StyledActivityItem = styled(ActivityItem)`
}
`;
-const ActivityItemWithEditing = styled(StyledActivityItem)`
+const ActivityItemWithEditing = styled(ActivityItemNote)`
&:hover {
${EditorTools} {
display: inline-block;
|
08de32fc6e1017f821073cd0986d97c73fa7a895
|
2018-06-04 23:47:24
|
Lyn Nagara
|
fix(dashboard): Prevent users without team:admin from navigating to team (#8634)
| false
|
Prevent users without team:admin from navigating to team (#8634)
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/organizationDashboard/index.jsx b/src/sentry/static/sentry/app/views/organizationDashboard/index.jsx
index 0acc2162fe078a..76ee4460c5e21f 100644
--- a/src/sentry/static/sentry/app/views/organizationDashboard/index.jsx
+++ b/src/sentry/static/sentry/app/views/organizationDashboard/index.jsx
@@ -45,6 +45,8 @@ class Dashboard extends React.Component {
const access = new Set(organization.access);
const teamsMap = new Map(teams.map(teamObj => [teamObj.slug, teamObj]));
+ const hasTeamAdminAccess = access.has('team:admin');
+
return (
<React.Fragment>
{favorites.length > 0 && (
@@ -69,9 +71,13 @@ class Dashboard extends React.Component {
team={team}
showBorder={showBorder}
title={
- <TeamLink to={`/settings/${organization.slug}/teams/${team.slug}/`}>
+ hasTeamAdminAccess ? (
+ <TeamLink to={`/settings/${organization.slug}/teams/${team.slug}/`}>
+ <IdBadge team={team} />
+ </TeamLink>
+ ) : (
<IdBadge team={team} />
- </TeamLink>
+ )
}
projects={projectsByTeam[slug]}
access={access}
|
109ab9b1c72234ab9f3a0f8c72feb5c49c60af91
|
2023-02-22 19:52:20
|
Priscila Oliveira
|
feat(stack-trace): Add amplitude analytics code - (#44951)
| false
|
Add amplitude analytics code - (#44951)
|
feat
|
diff --git a/static/app/components/events/traceEventDataSection.tsx b/static/app/components/events/traceEventDataSection.tsx
index f204129d572527..b3f1638bcd01bd 100644
--- a/static/app/components/events/traceEventDataSection.tsx
+++ b/static/app/components/events/traceEventDataSection.tsx
@@ -1,4 +1,10 @@
-import {AnchorHTMLAttributes, cloneElement, createContext, useState} from 'react';
+import {
+ AnchorHTMLAttributes,
+ cloneElement,
+ createContext,
+ useCallback,
+ useState,
+} from 'react';
import styled from '@emotion/styled';
import {Button} from 'sentry/components/button';
@@ -12,7 +18,8 @@ import {space} from 'sentry/styles/space';
import {PlatformType, Project} from 'sentry/types';
import {Event} from 'sentry/types/event';
import {STACK_TYPE} from 'sentry/types/stacktrace';
-import {isNativePlatform} from 'sentry/utils/platform';
+import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
+import {isMobilePlatform, isNativePlatform} from 'sentry/utils/platform';
import useApi from 'sentry/utils/useApi';
import useOrganization from 'sentry/utils/useOrganization';
@@ -91,6 +98,181 @@ export function TraceEventDataSection({
display: [],
});
+ const isMobile = isMobilePlatform(platform);
+
+ const handleFilterFramesChange = useCallback(
+ (val: 'full' | 'relevant') => {
+ const isFullOptionClicked = val === 'full';
+
+ trackAdvancedAnalyticsEvent(
+ isFullOptionClicked
+ ? 'stack-trace.full_stack_trace_clicked'
+ : 'stack-trace.most_relevant_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ }
+ );
+
+ setState(currentState => ({...currentState, fullStackTrace: isFullOptionClicked}));
+ },
+ [organization, platform, projectSlug, isMobile]
+ );
+
+ const handleSortByChange = useCallback(
+ (val: keyof typeof sortByOptions) => {
+ const isRecentFirst = val === 'recent-first';
+
+ trackAdvancedAnalyticsEvent(
+ isRecentFirst
+ ? 'stack-trace.sort_option_recent_first_clicked'
+ : 'stack-trace.sort_option_recent_last_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ }
+ );
+
+ setState(currentState => ({...currentState, sortBy: val}));
+ },
+ [organization, platform, projectSlug, isMobile]
+ );
+
+ const handleDisplayChange = useCallback(
+ (vals: (keyof typeof displayOptions)[]) => {
+ if (vals.includes('raw-stack-trace')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_raw_stack_trace_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: true,
+ }
+ );
+ } else if (state.display.includes('raw-stack-trace')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_raw_stack_trace_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: false,
+ }
+ );
+ }
+
+ if (vals.includes('absolute-addresses')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_absolute_addresses_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: true,
+ }
+ );
+ } else if (state.display.includes('absolute-addresses')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_absolute_addresses_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: false,
+ }
+ );
+ }
+
+ if (vals.includes('absolute-file-paths')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_absolute_file_paths_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: true,
+ }
+ );
+ } else if (state.display.includes('absolute-file-paths')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_absolute_file_paths_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: false,
+ }
+ );
+ }
+
+ if (vals.includes('minified')) {
+ trackAdvancedAnalyticsEvent(
+ platform.startsWith('javascript')
+ ? 'stack-trace.display_option_minified_clicked'
+ : 'stack-trace.display_option_unsymbolicated_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: true,
+ }
+ );
+ } else if (state.display.includes('minified')) {
+ trackAdvancedAnalyticsEvent(
+ platform.startsWith('javascript')
+ ? 'stack-trace.display_option_minified_clicked'
+ : 'stack-trace.display_option_unsymbolicated_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: false,
+ }
+ );
+ }
+
+ if (vals.includes('verbose-function-names')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_verbose_function_names_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: true,
+ }
+ );
+ } else if (state.display.includes('verbose-function-names')) {
+ trackAdvancedAnalyticsEvent(
+ 'stack-trace.display_option_verbose_function_names_clicked',
+ {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ checked: false,
+ }
+ );
+ }
+
+ setState(currentState => ({...currentState, display: vals}));
+ },
+ [organization, platform, projectSlug, isMobile, state]
+ );
+
function getDisplayOptions(): {
label: string;
value: keyof typeof displayOptions;
@@ -216,7 +398,7 @@ export function TraceEventDataSection({
size="xs"
aria-label={t('Filter frames')}
value={state.fullStackTrace ? 'full' : 'relevant'}
- onChange={val => setState({...state, fullStackTrace: val === 'full'})}
+ onChange={handleFilterFramesChange}
>
<SegmentedControl.Item key="relevant" disabled={!hasAppOnlyFrames}>
{t('Most Relevant')}
@@ -232,6 +414,14 @@ export function TraceEventDataSection({
size="xs"
href={rawStackTraceDownloadLink}
title={t('Download raw stack trace file')}
+ onClick={() => {
+ trackAdvancedAnalyticsEvent('stack-trace.download_clicked', {
+ organization,
+ project_slug: projectSlug,
+ platform,
+ is_mobile: isMobile,
+ });
+ }}
>
{t('Download')}
</Button>
@@ -245,7 +435,7 @@ export function TraceEventDataSection({
disabled={!!sortByTooltip}
position="bottom-end"
onChange={selectedOption => {
- setState({...state, sortBy: selectedOption.value});
+ handleSortByChange(selectedOption.value);
}}
value={state.sortBy}
options={Object.entries(sortByOptions).map(([value, label]) => ({
@@ -264,7 +454,7 @@ export function TraceEventDataSection({
triggerLabel=""
position="bottom-end"
value={state.display}
- onChange={opts => setState({...state, display: opts.map(opt => opt.value)})}
+ onChange={opts => handleDisplayChange(opts.map(opt => opt.value))}
options={[{label: t('Display'), options: getDisplayOptions()}]}
/>
</ButtonBar>
diff --git a/static/app/utils/analytics/stackTraceAnalyticsEvents.tsx b/static/app/utils/analytics/stackTraceAnalyticsEvents.tsx
new file mode 100644
index 00000000000000..712ce8cbc8043f
--- /dev/null
+++ b/static/app/utils/analytics/stackTraceAnalyticsEvents.tsx
@@ -0,0 +1,85 @@
+export type StackTraceEventParameters = {
+ 'stack-trace.display_option_absolute_addresses_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.display_option_absolute_file_paths_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.display_option_minified_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.display_option_raw_stack_trace_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.display_option_unsymbolicated_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.display_option_verbose_function_names_clicked': {
+ checked: boolean;
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.download_clicked': {
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.full_stack_trace_clicked': {
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.most_relevant_clicked': {
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.sort_option_recent_first_clicked': {
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+ 'stack-trace.sort_option_recent_last_clicked': {
+ is_mobile: boolean;
+ project_slug: string;
+ platform?: string;
+ };
+};
+
+export const stackTraceEventMap: Record<keyof StackTraceEventParameters, string> = {
+ 'stack-trace.display_option_absolute_addresses_clicked':
+ 'Stack Trace: Display Option - Absolute Addresses - Clicked',
+ 'stack-trace.display_option_absolute_file_paths_clicked':
+ 'Stack Trace: Display Option - Absolute File Paths - Clicked',
+ 'stack-trace.display_option_minified_clicked':
+ 'Stack Trace: Display Option - Minified - Clicked',
+ 'stack-trace.display_option_raw_stack_trace_clicked':
+ 'Stack Trace: Display Option - Raw Stack Trace - Clicked',
+ 'stack-trace.display_option_unsymbolicated_clicked':
+ 'Stack Trace: Display Option - Unsymbolicated - Clicked',
+ 'stack-trace.display_option_verbose_function_names_clicked':
+ 'Stack Trace: Display Option - Verbose Function Names - Clicked',
+ 'stack-trace.download_clicked': 'Stack Trace: Download - Clicked',
+ 'stack-trace.full_stack_trace_clicked': 'Stack Trace: Full Stack Trace - Clicked',
+ 'stack-trace.most_relevant_clicked': 'Stack Trace: Most Relevant - Clicked',
+ 'stack-trace.sort_option_recent_first_clicked':
+ 'Stack Trace: Sort Option - Recent First - Clicked',
+ 'stack-trace.sort_option_recent_last_clicked':
+ 'Stack Trace: Sort Option - Recent Last - Clicked',
+};
diff --git a/static/app/utils/analytics/trackAdvancedAnalyticsEvent.tsx b/static/app/utils/analytics/trackAdvancedAnalyticsEvent.tsx
index c501e03781e30c..6d9bfd37461507 100644
--- a/static/app/utils/analytics/trackAdvancedAnalyticsEvent.tsx
+++ b/static/app/utils/analytics/trackAdvancedAnalyticsEvent.tsx
@@ -19,6 +19,7 @@ import {releasesEventMap, ReleasesEventParameters} from './releasesAnalyticsEven
import {replayEventMap, ReplayEventParameters} from './replayAnalyticsEvents';
import {searchEventMap, SearchEventParameters} from './searchAnalyticsEvents';
import {settingsEventMap, SettingsEventParameters} from './settingsAnalyticsEvents';
+import {stackTraceEventMap, StackTraceEventParameters} from './stackTraceAnalyticsEvents';
import {TeamInsightsEventParameters, workflowEventMap} from './workflowAnalyticsEvents';
type EventParameters = GrowthEventParameters &
@@ -35,7 +36,8 @@ type EventParameters = GrowthEventParameters &
SettingsEventParameters &
TeamInsightsEventParameters &
DynamicSamplingEventParameters &
- HeartbeatEventParameters;
+ HeartbeatEventParameters &
+ StackTraceEventParameters;
const allEventMap: Record<string, string | null> = {
...coreUIEventMap,
@@ -53,6 +55,7 @@ const allEventMap: Record<string, string | null> = {
...workflowEventMap,
...dynamicSamplingEventMap,
...heartbeatEventMap,
+ ...stackTraceEventMap,
};
/**
|
f9d5425b4d156137f94a4a744d84361c71ce7d8c
|
2021-10-15 18:10:34
|
Armen Zambrano G
|
feat(dev): Run dev env workflow when .pre-commit-config.yaml changes (#29331)
| false
|
Run dev env workflow when .pre-commit-config.yaml changes (#29331)
|
feat
|
diff --git a/.github/workflows/development-environment.yml b/.github/workflows/development-environment.yml
index 0a53c8e40d6097..fcdaa65dcae500 100644
--- a/.github/workflows/development-environment.yml
+++ b/.github/workflows/development-environment.yml
@@ -2,6 +2,7 @@ name: dev env
on:
pull_request:
paths:
+ - '.pre-commit-config.yaml'
- 'Makefile'
- '.github/actions/*'
- '.github/workflows/development-environment.yml'
|
d6c801c87266b1e4aa1647648c156ba5556a77c7
|
2024-01-23 04:18:43
|
anthony sottile
|
ref: speed up test_perf_issue_slow_db_issue_is_created (#63592)
| false
|
speed up test_perf_issue_slow_db_issue_is_created (#63592)
|
ref
|
diff --git a/tests/sentry/event_manager/test_event_manager.py b/tests/sentry/event_manager/test_event_manager.py
index 987b39314a95ae..4a1e867488b76c 100644
--- a/tests/sentry/event_manager/test_event_manager.py
+++ b/tests/sentry/event_manager/test_event_manager.py
@@ -2451,14 +2451,10 @@ def test_perf_issue_creation_over_ignored_threshold(self):
)
def test_perf_issue_slow_db_issue_is_created(self):
def attempt_to_generate_slow_db_issue() -> Event:
- for _ in range(100):
- event = self.create_performance_issue(
- event_data=make_event(**get_event("slow-db-spans")),
- issue_type=PerformanceSlowDBQueryGroupType,
- )
- last_event = event
-
- return last_event
+ return self.create_performance_issue(
+ event_data=make_event(**get_event("slow-db-spans")),
+ issue_type=PerformanceSlowDBQueryGroupType,
+ )
# Should not create the group without the feature flag
last_event = attempt_to_generate_slow_db_issue()
|
a96df738a32f822415e0f2404df832c4fec440ca
|
2025-03-13 19:13:16
|
Leander Rodrigues
|
ref(fe): Convert `<IntegrationDetailedView />` to FC (#86954)
| false
|
Convert `<IntegrationDetailedView />` to FC (#86954)
|
ref
|
diff --git a/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx b/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
index 76628aea1b71c0..2169c2dd647b4f 100644
--- a/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
+++ b/static/app/views/settings/organizationIntegrations/abstractIntegrationDetailedView.tsx
@@ -19,7 +19,7 @@ import RequestIntegrationButton from './integrationRequest/RequestIntegrationBut
export type Tab = 'overview' | 'configurations' | 'features';
-interface AlertType extends AlertProps {
+export interface AlertType extends AlertProps {
text: string;
}
diff --git a/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.tsx b/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.tsx
index cfcaf3ce52f947..23cff66a6b6047 100644
--- a/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.tsx
+++ b/static/app/views/settings/organizationIntegrations/integrationDetailedView.spec.tsx
@@ -1,8 +1,7 @@
import {GitHubIntegrationFixture} from 'sentry-fixture/githubIntegration';
import {GitHubIntegrationProviderFixture} from 'sentry-fixture/githubIntegrationProvider';
-import {LocationFixture} from 'sentry-fixture/locationFixture';
import {OrganizationFixture} from 'sentry-fixture/organization';
-import {RouteComponentPropsFixture} from 'sentry-fixture/routeComponentPropsFixture';
+import {RouterFixture} from 'sentry-fixture/routerFixture';
import {render, screen, userEvent, waitFor} from 'sentry-test/reactTestingLibrary';
@@ -10,15 +9,15 @@ import IntegrationDetailedView from 'sentry/views/settings/organizationIntegrati
describe('IntegrationDetailedView', function () {
const ENDPOINT = '/organizations/org-slug/';
- const org = OrganizationFixture({
+ const organization = OrganizationFixture({
access: ['org:integrations', 'org:write'],
});
beforeEach(() => {
MockApiClient.clearMockResponses();
-
MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/config/integrations/?provider_key=bitbucket`,
+ url: `/organizations/${organization.slug}/config/integrations/`,
+ match: [MockApiClient.matchQuery({provider_key: 'bitbucket'})],
body: {
providers: [
{
@@ -52,9 +51,9 @@ describe('IntegrationDetailedView', function () {
],
},
});
-
MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/integrations/?provider_key=bitbucket&includeConfig=0`,
+ url: `/organizations/${organization.slug}/integrations/`,
+ match: [MockApiClient.matchQuery({provider_key: 'bitbucket', includeConfig: 0})],
body: [
{
accountType: null,
@@ -77,29 +76,36 @@ describe('IntegrationDetailedView', function () {
},
],
});
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/config/integrations/`,
+ match: [MockApiClient.matchQuery({provider_key: 'github'})],
+ body: {
+ providers: [GitHubIntegrationProviderFixture()],
+ },
+ });
+ MockApiClient.addMockResponse({
+ url: `/organizations/${organization.slug}/integrations/`,
+ match: [MockApiClient.matchQuery({provider_key: 'github', includeConfig: 0})],
+ body: [GitHubIntegrationFixture()],
+ });
});
- it('shows integration name, status, and install button', function () {
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'bitbucket'}}
- location={LocationFixture({query: {}})}
- />
- );
+ it('shows integration name, status, and install button', async function () {
+ const router = RouterFixture({params: {integrationSlug: 'bitbucket'}});
+ render(<IntegrationDetailedView />, {organization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
expect(screen.getByText('Bitbucket')).toBeInTheDocument();
expect(screen.getByText('Installed')).toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Add integration'})).toBeEnabled();
});
- it('view configurations', function () {
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'bitbucket'}}
- location={LocationFixture({query: {tab: 'configurations'}})}
- />
- );
+ it('view configurations', async function () {
+ const router = RouterFixture({
+ params: {integrationSlug: 'bitbucket'},
+ location: {query: {tab: 'configurations'}},
+ });
+ render(<IntegrationDetailedView />, {organization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
expect(screen.getByTestId('integration-name')).toHaveTextContent(
'{fb715533-bbd7-4666-aa57-01dc93dd9cc0}'
@@ -107,126 +113,50 @@ describe('IntegrationDetailedView', function () {
expect(screen.getByRole('button', {name: 'Configure'})).toBeEnabled();
});
- it('disables configure for members without access', function () {
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'bitbucket'}}
- location={LocationFixture({query: {tab: 'configurations'}})}
- />,
- {organization: OrganizationFixture({access: ['org:read']})}
- );
+ it('disables configure for members without access', async function () {
+ const router = RouterFixture({
+ params: {integrationSlug: 'bitbucket'},
+ location: {query: {tab: 'configurations'}},
+ });
+ const lowerAccessOrganization = OrganizationFixture({access: ['org:read']});
+ render(<IntegrationDetailedView />, {organization: lowerAccessOrganization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Configure'})).toBeDisabled();
});
- it('allows members to configure github/gitlab', function () {
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/config/integrations/?provider_key=github`,
- body: {
- providers: [GitHubIntegrationProviderFixture()],
- },
- });
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/integrations/?provider_key=github&includeConfig=0`,
- body: [
- {
- accountType: null,
- configData: {},
- configOrganization: [],
- domainName: 'github.com/%7Bfb715533-bbd7-4666-aa57-01dc93dd9cc0%7D',
- icon: 'https://secure.gravatar.com/avatar/8b4cb68e40b74c90427d8262256bd1c8?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FNN-0.png',
- id: '4',
- name: '{fb715533-bbd7-4666-aa57-01dc93dd9cc0}',
- provider: {
- aspects: {},
- canAdd: true,
- canDisable: false,
- features: ['commits', 'issue-basic'],
- key: 'github',
- name: 'GitHub',
- slug: 'github',
- },
- status: 'active',
- },
- ],
+ it('allows members to configure github/gitlab', async function () {
+ const router = RouterFixture({
+ params: {integrationSlug: 'github'},
+ location: {query: {tab: 'configurations'}},
});
-
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'github'}}
- location={LocationFixture({query: {tab: 'configurations'}})}
- />,
- {organization: OrganizationFixture({access: ['org:read']})}
- );
+ const lowerAccessOrganization = OrganizationFixture({access: ['org:read']});
+ render(<IntegrationDetailedView />, {organization: lowerAccessOrganization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
expect(screen.getByRole('button', {name: 'Configure'})).toBeEnabled();
});
- it('shows features tab for github only', function () {
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/config/integrations/?provider_key=github`,
- body: {
- providers: [GitHubIntegrationProviderFixture()],
- },
- });
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/integrations/?provider_key=github&includeConfig=0`,
- body: [
- {
- accountType: null,
- configData: {},
- configOrganization: [],
- domainName: 'github.com/%7Bfb715533-bbd7-4666-aa57-01dc93dd9cc0%7D',
- icon: 'https://secure.gravatar.com/avatar/8b4cb68e40b74c90427d8262256bd1c8?d=https%3A%2F%2Favatar-management--avatars.us-west-2.prod.public.atl-paas.net%2Finitials%2FNN-0.png',
- id: '4',
- name: '{fb715533-bbd7-4666-aa57-01dc93dd9cc0}',
- provider: {
- aspects: {},
- canAdd: true,
- canDisable: false,
- features: ['commits', 'issue-basic'],
- key: 'github',
- name: 'GitHub',
- slug: 'github',
- },
- status: 'active',
- },
- ],
+ it('shows features tab for github only', async function () {
+ const router = RouterFixture({
+ params: {integrationSlug: 'github'},
});
-
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'github'}}
- organization={org}
- location={LocationFixture({query: {}})}
- />
- );
+ render(<IntegrationDetailedView />, {organization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
expect(screen.getByText('features')).toBeInTheDocument();
});
it('cannot enable PR bot without GitHub integration', async function () {
MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/config/integrations/?provider_key=github`,
- body: {
- providers: [GitHubIntegrationProviderFixture()],
- },
- });
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/integrations/?provider_key=github&includeConfig=0`,
+ url: `/organizations/${organization.slug}/integrations/`,
+ match: [MockApiClient.matchQuery({provider_key: 'github', includeConfig: 0})],
body: [],
});
-
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'github'}}
- organization={org}
- location={LocationFixture({query: {}})}
- />
- );
+ const router = RouterFixture({
+ params: {integrationSlug: 'github'},
+ });
+ render(<IntegrationDetailedView />, {organization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
await userEvent.click(screen.getByText('features'));
@@ -240,25 +170,12 @@ describe('IntegrationDetailedView', function () {
});
it('can enable github features', async function () {
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/config/integrations/?provider_key=github`,
- body: {
- providers: [GitHubIntegrationProviderFixture()],
- },
+ const router = RouterFixture({
+ params: {integrationSlug: 'github'},
});
+ render(<IntegrationDetailedView />, {organization, router});
+ expect(await screen.findByTestId('loading-indicator')).not.toBeInTheDocument();
- MockApiClient.addMockResponse({
- url: `/organizations/${org.slug}/integrations/?provider_key=github&includeConfig=0`,
- body: [GitHubIntegrationFixture()],
- });
- render(
- <IntegrationDetailedView
- {...RouteComponentPropsFixture()}
- params={{integrationSlug: 'github'}}
- organization={org}
- location={LocationFixture({query: {}})}
- />
- );
await userEvent.click(screen.getByText('features'));
const mock = MockApiClient.addMockResponse({
diff --git a/static/app/views/settings/organizationIntegrations/integrationDetailedView.tsx b/static/app/views/settings/organizationIntegrations/integrationDetailedView.tsx
index 4651db0ce377a9..21587eb6a9d455 100644
--- a/static/app/views/settings/organizationIntegrations/integrationDetailedView.tsx
+++ b/static/app/views/settings/organizationIntegrations/integrationDetailedView.tsx
@@ -1,29 +1,47 @@
-import {Fragment} from 'react';
+import {Fragment, useCallback, useMemo} from 'react';
import styled from '@emotion/styled';
import {addErrorMessage} from 'sentry/actionCreators/indicator';
import type {RequestOptions} from 'sentry/api';
import {Alert} from 'sentry/components/core/alert';
-import type DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
import Form from 'sentry/components/forms/form';
import JsonForm from 'sentry/components/forms/jsonForm';
import type {Data, JsonFormObject} from 'sentry/components/forms/types';
import HookOrDefault from 'sentry/components/hookOrDefault';
+import LoadingError from 'sentry/components/loadingError';
+import LoadingIndicator from 'sentry/components/loadingIndicator';
import Panel from 'sentry/components/panels/panel';
import PanelItem from 'sentry/components/panels/panelItem';
import {t} from 'sentry/locale';
+import PluginIcon from 'sentry/plugins/components/pluginIcon';
import {space} from 'sentry/styles/space';
import type {ObjectStatus} from 'sentry/types/core';
import type {Integration, IntegrationProvider} from 'sentry/types/integrations';
-import {getAlertText, getIntegrationStatus} from 'sentry/utils/integrationUtil';
-import normalizeUrl from 'sentry/utils/url/normalizeUrl';
-import withOrganization from 'sentry/utils/withOrganization';
-import BreadcrumbTitle from 'sentry/views/settings/components/settingsBreadcrumb/breadcrumbTitle';
+import {
+ getAlertText,
+ getIntegrationStatus,
+ trackIntegrationAnalytics,
+} from 'sentry/utils/integrationUtil';
+import {
+ type ApiQueryKey,
+ setApiQueryData,
+ useApiQuery,
+ useQueryClient,
+} from 'sentry/utils/queryClient';
+import useApi from 'sentry/utils/useApi';
+import {useLocation} from 'sentry/utils/useLocation';
+import {useNavigate} from 'sentry/utils/useNavigate';
+import useOrganization from 'sentry/utils/useOrganization';
+import {useParams} from 'sentry/utils/useParams';
+import type {
+ AlertType,
+ Tab,
+} from 'sentry/views/settings/organizationIntegrations/abstractIntegrationDetailedView';
+import IntegrationLayout from 'sentry/views/settings/organizationIntegrations/detailedView/integrationLayout';
+import {useIntegrationTabs} from 'sentry/views/settings/organizationIntegrations/detailedView/useIntegrationTabs';
import IntegrationButton from 'sentry/views/settings/organizationIntegrations/integrationButton';
import {IntegrationContext} from 'sentry/views/settings/organizationIntegrations/integrationContext';
-import type {Tab} from './abstractIntegrationDetailedView';
-import AbstractIntegrationDetailedView from './abstractIntegrationDetailedView';
import InstalledIntegration from './installedIntegration';
// Show the features tab if the org has features for the integration
@@ -39,89 +57,101 @@ const FirstPartyIntegrationAdditionalCTA = HookOrDefault({
defaultComponent: () => null,
});
-type State = {
- configurations: Integration[];
- information: {providers: IntegrationProvider[]};
+type IntegrationInformation = {
+ providers: IntegrationProvider[];
};
-class IntegrationDetailedView extends AbstractIntegrationDetailedView<
- AbstractIntegrationDetailedView['props'],
- State & AbstractIntegrationDetailedView['state']
-> {
- tabs: Tab[] = ['overview', 'configurations', 'features'];
+function makeIntegrationQueryKey({
+ orgSlug,
+ integrationSlug,
+}: {
+ integrationSlug: string;
+ orgSlug: string;
+}): ApiQueryKey {
+ return [
+ `/organizations/${orgSlug}/integrations/`,
+ {
+ query: {
+ provider_key: integrationSlug,
+ includeConfig: 0,
+ },
+ },
+ ];
+}
- getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
- const {organization} = this.props;
- const {integrationSlug} = this.props.params;
+export default function IntegrationDetailedView() {
+ const tabs: Tab[] = useMemo(() => ['overview', 'configurations', 'features'], []);
+ const api = useApi({persistInFlight: true});
+ const queryClient = useQueryClient();
+ const {activeTab, setActiveTab} = useIntegrationTabs<Tab>({
+ initialTab: 'overview',
+ });
+ const navigate = useNavigate();
+ const location = useLocation();
+ const organization = useOrganization();
+ const {integrationSlug} = useParams<{integrationSlug: string}>();
+
+ const {
+ data: information,
+ isPending: isInformationPending,
+ isError: isInformationError,
+ } = useApiQuery<IntegrationInformation>(
+ [
+ `/organizations/${organization.slug}/config/integrations/`,
+ {
+ query: {
+ provider_key: integrationSlug,
+ },
+ },
+ ],
+ {
+ staleTime: Infinity,
+ retry: false,
+ }
+ );
+
+ const {
+ data: configurations = [],
+ isPending: isConfigurationsPending,
+ isError: isConfigurationsError,
+ } = useApiQuery<Integration[]>(
+ makeIntegrationQueryKey({orgSlug: organization.slug, integrationSlug}),
+ {
+ staleTime: Infinity,
+ retry: false,
+ }
+ );
+
+ const integrationType = 'first_party';
+ const provider = information?.providers[0];
+ const description = provider?.metadata.description ?? '';
+ const author = provider?.metadata.author ?? '';
+ const resourceLinks = useMemo(() => {
return [
- [
- 'information',
- `/organizations/${organization.slug}/config/integrations/?provider_key=${integrationSlug}`,
- ],
- [
- 'configurations',
- `/organizations/${organization.slug}/integrations/?provider_key=${integrationSlug}&includeConfig=0`,
- ],
+ {url: provider?.metadata.source_url ?? '', title: 'View Source'},
+ {url: provider?.metadata.issue_url ?? '', title: 'Report Issue'},
];
- }
-
- get integrationType() {
- return 'first_party' as const;
- }
-
- get provider() {
- return this.state.information.providers[0]!;
- }
-
- get description() {
- return this.metadata.description;
- }
-
- get author() {
- return this.metadata.author;
- }
-
- get alerts() {
- const provider = this.provider;
- const metadata = this.metadata;
+ }, [provider]);
+ const alerts: AlertType[] = useMemo(() => {
// The server response for integration installations includes old icon CSS classes
// We map those to the currently in use values to their react equivalents
// and fallback to IconFlag just in case.
- const alerts = (metadata.aspects.alerts || []).map(item => ({
+ const alertList = (provider?.metadata.aspects.alerts || []).map(item => ({
...item,
showIcon: true,
}));
- if (!provider.canAdd && metadata.aspects.externalInstall) {
- alerts.push({
+ if (!provider?.canAdd && provider?.metadata.aspects.externalInstall) {
+ alertList.push({
type: 'warning',
showIcon: true,
- text: metadata.aspects.externalInstall.noticeText,
+ text: provider?.metadata.aspects.externalInstall.noticeText,
});
}
- return alerts;
- }
-
- get resourceLinks() {
- const metadata = this.metadata;
- return [
- {url: metadata.source_url, title: 'View Source'},
- {url: metadata.issue_url, title: 'Report Issue'},
- ];
- }
-
- get metadata() {
- return this.provider.metadata;
- }
-
- get isEnabled() {
- return this.state.configurations.length > 0;
- }
-
- get installationStatus() {
- // TODO: add transations
- const {configurations} = this.state;
- const statusList = configurations.map(getIntegrationStatus);
+ return alertList;
+ }, [provider]);
+ const installationStatus = useMemo(() => {
+ const statusList = configurations?.map(getIntegrationStatus);
// if we have conflicting statuses, we have a priority order
if (statusList.includes('active')) {
return 'Installed';
@@ -133,75 +163,89 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
return 'Pending Deletion';
}
return 'Not Installed';
- }
-
- get integrationName() {
- return this.provider.name;
- }
-
- get featureData() {
- return this.metadata.features;
- }
+ }, [configurations]);
+ const integrationName = provider?.name ?? '';
+ const featureData = useMemo(() => {
+ return provider?.metadata.features ?? [];
+ }, [provider]);
+
+ const onTabChange = useCallback(
+ (tab: Tab) => {
+ setActiveTab(tab);
+ trackIntegrationAnalytics('integrations.integration_tab_clicked', {
+ view: 'integrations_directory_integration_detail',
+ integration: integrationSlug,
+ integration_type: integrationType,
+ already_installed: installationStatus !== 'Not Installed', // pending counts as installed here
+ organization,
+ integration_tab: tab,
+ });
+ },
+ [setActiveTab, integrationSlug, integrationType, installationStatus, organization]
+ );
- renderTabs() {
- // TODO: Convert to styled component
- const tabs = integrationFeatures.includes(this.provider.key)
- ? this.tabs
- : this.tabs.filter(tab => tab !== 'features');
+ const renderTabs = useCallback(() => {
+ const displayTabs = integrationFeatures.includes(provider?.key ?? '')
+ ? tabs
+ : tabs.filter(tab => tab !== 'features');
return (
- <ul className="nav nav-tabs border-bottom" style={{paddingTop: '30px'}}>
- {tabs.map(tabName => (
- <li
- key={tabName}
- className={this.state.tab === tabName ? 'active' : ''}
- onClick={() => this.onTabChange(tabName)}
- >
- <CapitalizedLink>{this.getTabDisplay(tabName)}</CapitalizedLink>
- </li>
- ))}
- </ul>
+ <IntegrationLayout.Tabs
+ tabs={displayTabs}
+ activeTab={activeTab}
+ onTabChange={onTabChange}
+ />
);
- }
+ }, [provider, tabs, activeTab, onTabChange]);
- onInstall = (integration: Integration) => {
- // send the user to the configure integration view for that integration
- const {organization} = this.props;
- this.props.router.push(
- normalizeUrl(
+ const onInstall = useCallback(
+ (integration: Integration) => {
+ // send the user to the configure integration view for that integration
+ navigate(
`/settings/${organization.slug}/integrations/${integration.provider.key}/${integration.id}/`
- )
- );
- };
-
- onRemove = (integration: Integration) => {
- const {organization} = this.props;
-
- const origIntegrations = [...this.state.configurations];
-
- const integrations = this.state.configurations.map(i =>
- i.id === integration.id
- ? {...i, organizationIntegrationStatus: 'pending_deletion' as ObjectStatus}
- : i
- );
-
- this.setState({configurations: integrations});
-
- const options: RequestOptions = {
- method: 'DELETE',
- error: () => {
- this.setState({configurations: origIntegrations});
- addErrorMessage(t('Failed to remove Integration'));
- },
- };
-
- this.api.request(
- `/organizations/${organization.slug}/integrations/${integration.id}/`,
- options
- );
- };
-
- onDisable = (integration: Integration) => {
+ );
+ },
+ [organization.slug, navigate]
+ );
+
+ const onRemove = useCallback(
+ (integration: Integration) => {
+ const originalConfigurations = [...configurations];
+
+ const updatedConfigurations = configurations.map(config =>
+ config.id === integration.id
+ ? {...config, organizationIntegrationStatus: 'pending_deletion' as ObjectStatus}
+ : config
+ );
+
+ setApiQueryData<Integration[]>(
+ queryClient,
+ makeIntegrationQueryKey({orgSlug: organization.slug, integrationSlug}),
+ updatedConfigurations
+ );
+
+ const options: RequestOptions = {
+ method: 'DELETE',
+ error: () => {
+ setApiQueryData<Integration[]>(
+ queryClient,
+ makeIntegrationQueryKey({orgSlug: organization.slug, integrationSlug}),
+ originalConfigurations
+ );
+ addErrorMessage(t('Failed to remove Integration'));
+ },
+ };
+
+ // XXX: We can probably convert this to a mutation, but trying to avoid it for the FC conversion.
+ api.request(
+ `/organizations/${organization.slug}/integrations/${integration.id}/`,
+ options
+ );
+ },
+ [api, configurations, integrationSlug, organization.slug, queryClient]
+ );
+
+ const onDisable = useCallback((integration: Integration) => {
let url: string;
if (!integration.domainName) {
@@ -216,72 +260,79 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
}
window.open(url, '_blank');
- };
-
- handleExternalInstall = () => {
- this.trackIntegrationAnalytics('integrations.installation_start');
- };
+ }, []);
- renderAlert() {
- return (
- <FirstPartyIntegrationAlert
- integrations={this.state.configurations ?? []}
- hideCTA
- />
- );
- }
+ const renderTopButton = useCallback(
+ (disabledFromFeatures: boolean, userHasAccess: boolean) => {
+ const queryParams = new URLSearchParams(location.search);
+ const referrer = queryParams.get('referrer');
- renderAdditionalCTA() {
- return (
- <FirstPartyIntegrationAdditionalCTA
- integrations={this.state.configurations ?? []}
- />
- );
- }
+ const buttonProps = {
+ size: 'sm',
+ priority: 'primary',
+ 'data-test-id': 'install-button',
+ disabled: disabledFromFeatures,
+ };
- renderTopButton(disabledFromFeatures: boolean, userHasAccess: boolean) {
- const provider = this.provider;
- const location = this.props.location;
- const queryParams = new URLSearchParams(location.search);
- const referrer = queryParams.get('referrer');
-
- const buttonProps = {
- size: 'sm',
- priority: 'primary',
- 'data-test-id': 'install-button',
- disabled: disabledFromFeatures,
- };
+ if (!provider) {
+ return null;
+ }
- return (
- <IntegrationContext.Provider
- value={{
- provider,
- type: this.integrationType,
- installStatus: this.installationStatus,
- analyticsParams: {
- view: 'integrations_directory_integration_detail',
- already_installed: this.installationStatus !== 'Not Installed',
- ...(referrer && {referrer}),
- },
- }}
- >
- <StyledIntegrationButton
- userHasAccess={userHasAccess}
- onAddIntegration={this.onInstall}
- onExternalClick={this.handleExternalInstall}
- buttonProps={buttonProps}
+ return (
+ <IntegrationContext.Provider
+ value={{
+ provider,
+ type: integrationType,
+ installStatus: installationStatus,
+ analyticsParams: {
+ view: 'integrations_directory_integration_detail',
+ already_installed: installationStatus !== 'Not Installed',
+ ...(referrer && {referrer}),
+ },
+ }}
+ >
+ <StyledIntegrationButton
+ userHasAccess={userHasAccess}
+ onAddIntegration={onInstall}
+ onExternalClick={() => {
+ trackIntegrationAnalytics('integrations.installation_start', {
+ view: 'integrations_directory_integration_detail',
+ integration: integrationSlug,
+ integration_type: integrationType,
+ already_installed: installationStatus !== 'Not Installed',
+ organization,
+ });
+ }}
+ buttonProps={buttonProps}
+ />
+ </IntegrationContext.Provider>
+ );
+ },
+ [
+ provider,
+ integrationType,
+ installationStatus,
+ onInstall,
+ organization,
+ integrationSlug,
+ location.search,
+ ]
+ );
+
+ const renderConfigurations = useCallback(() => {
+ if (!configurations.length || !provider) {
+ return (
+ <IntegrationLayout.EmptyConfigurations
+ action={
+ <IntegrationLayout.AddInstallButton
+ featureData={featureData}
+ hideButtonIfDisabled
+ requiresAccess
+ renderTopButton={renderTopButton}
+ />
+ }
/>
- </IntegrationContext.Provider>
- );
- }
-
- renderConfigurations() {
- const {configurations} = this.state;
- const {organization} = this.props;
- const provider = this.provider;
-
- if (!configurations.length) {
- return this.renderEmptyConfigurations();
+ );
}
const alertText = getAlertText(configurations);
@@ -302,10 +353,18 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
organization={organization}
provider={provider}
integration={integration}
- onRemove={this.onRemove}
- onDisable={this.onDisable}
+ onRemove={onRemove}
+ onDisable={onDisable}
data-test-id={integration.id}
- trackIntegrationAnalytics={this.trackIntegrationAnalytics}
+ trackIntegrationAnalytics={eventKey => {
+ trackIntegrationAnalytics(eventKey, {
+ view: 'integrations_directory_integration_detail',
+ integration: integrationSlug,
+ integration_type: integrationType,
+ already_installed: installationStatus !== 'Not Installed',
+ organization,
+ });
+ }}
requiresUpgrade={!!alertText}
/>
</PanelItem>
@@ -313,11 +372,20 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
</Panel>
</Fragment>
);
- }
-
- getSlackFeatures(): [JsonFormObject[], Data] {
- const {configurations} = this.state;
- const {organization} = this.props;
+ }, [
+ configurations,
+ provider,
+ onRemove,
+ onDisable,
+ featureData,
+ installationStatus,
+ integrationSlug,
+ integrationType,
+ organization,
+ renderTopButton,
+ ]);
+
+ const getSlackFeatures = useCallback((): [JsonFormObject[], Data] => {
const hasIntegration = configurations ? configurations.length > 0 : false;
const forms: JsonFormObject[] = [
@@ -357,11 +425,9 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
};
return [forms, initialData];
- }
+ }, [organization, configurations]);
- getGithubFeatures(): [JsonFormObject[], Data] {
- const {configurations} = this.state;
- const {organization} = this.props;
+ const getGithubFeatures = useCallback((): [JsonFormObject[], Data] => {
const hasIntegration = configurations ? configurations.length > 0 : false;
const forms: JsonFormObject[] = [
@@ -414,21 +480,20 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
};
return [forms, initialData];
- }
+ }, [organization, configurations]);
- renderFeatures() {
- const {organization} = this.props;
+ const renderFeatures = useCallback(() => {
const endpoint = `/organizations/${organization.slug}/`;
const hasOrgWrite = organization.access.includes('org:write');
let forms: JsonFormObject[], initialData: Data;
- switch (this.provider.key) {
+ switch (provider?.key) {
case 'github': {
- [forms, initialData] = this.getGithubFeatures();
+ [forms, initialData] = getGithubFeatures();
break;
}
case 'slack': {
- [forms, initialData] = this.getSlackFeatures();
+ [forms, initialData] = getSlackFeatures();
break;
}
default:
@@ -451,29 +516,60 @@ class IntegrationDetailedView extends AbstractIntegrationDetailedView<
/>
</Form>
);
+ }, [organization, provider, getGithubFeatures, getSlackFeatures]);
+
+ if (isInformationPending || isConfigurationsPending) {
+ return <LoadingIndicator />;
}
- renderBody() {
- return (
- <Fragment>
- <BreadcrumbTitle routes={this.props.routes} title={this.integrationName} />
- {this.renderAlert()}
- {this.renderTopSection()}
- {this.renderTabs()}
- {this.state.tab === 'overview'
- ? this.renderInformationCard()
- : this.state.tab === 'configurations'
- ? this.renderConfigurations()
- : this.renderFeatures()}
- </Fragment>
- );
+ if (isInformationError || isConfigurationsError) {
+ return <LoadingError message={t('There was an error loading this integration.')} />;
}
-}
-export default withOrganization(IntegrationDetailedView);
-const CapitalizedLink = styled('a')`
- text-transform: capitalize;
-`;
+ return (
+ <IntegrationLayout.Body
+ integrationName={integrationName}
+ alert={<FirstPartyIntegrationAlert integrations={configurations} hideCTA />}
+ topSection={
+ <IntegrationLayout.TopSection
+ featureData={featureData}
+ integrationName={integrationName}
+ installationStatus={installationStatus}
+ integrationIcon={<PluginIcon pluginId={integrationSlug} size={50} />}
+ addInstallButton={
+ <IntegrationLayout.AddInstallButton
+ featureData={featureData}
+ hideButtonIfDisabled={false}
+ requiresAccess
+ renderTopButton={renderTopButton}
+ />
+ }
+ additionalCTA={
+ <FirstPartyIntegrationAdditionalCTA integrations={configurations} />
+ }
+ />
+ }
+ tabs={renderTabs()}
+ content={
+ activeTab === 'overview' ? (
+ <IntegrationLayout.InformationCard
+ integrationSlug={integrationSlug}
+ description={description}
+ alerts={alerts}
+ featureData={featureData}
+ author={author}
+ resourceLinks={resourceLinks}
+ permissions={null}
+ />
+ ) : activeTab === 'configurations' ? (
+ renderConfigurations()
+ ) : (
+ renderFeatures()
+ )
+ }
+ />
+ );
+}
const StyledIntegrationButton = styled(IntegrationButton)`
margin-bottom: ${space(1)};
|
b75133d00bfa8048e3068ba87ab1ef1a3fddb0ed
|
2018-06-06 23:03:03
|
Lauryn Brown
|
feat(integrations): Default Identity (#8647)
| false
|
Default Identity (#8647)
|
feat
|
diff --git a/src/sentry/integrations/base.py b/src/sentry/integrations/base.py
index d36ee16202f645..8a0e2411a4400f 100644
--- a/src/sentry/integrations/base.py
+++ b/src/sentry/integrations/base.py
@@ -72,6 +72,10 @@ class is just a descriptor for how that object functions, and what behavior
# can the integration be enabled specifically for projects?
can_add_project = False
+ # if the integration has no application-style access token, associate
+ # the installer's identity to the organization integration
+ needs_default_identity = False
+
# can be any number of IntegrationFeatures
features = frozenset()
diff --git a/src/sentry/integrations/pipeline.py b/src/sentry/integrations/pipeline.py
index dc8823973501b4..44c5fe326abcc8 100644
--- a/src/sentry/integrations/pipeline.py
+++ b/src/sentry/integrations/pipeline.py
@@ -63,8 +63,6 @@ def _finish_pipeline(self, data):
else:
integration = ensure_integration(self.provider.key, data)
- org_integration = integration.add_organization(self.organization.id)
-
# Does this integration provide a user identity for the user setting up
# the integration?
identity = data.get('user_identity')
@@ -88,7 +86,7 @@ def _finish_pipeline(self, data):
}
try:
- ident, created = Identity.objects.get_or_create(
+ identity_model, created = Identity.objects.get_or_create(
idp=idp,
user=self.request.user,
external_id=identity['external_id'],
@@ -96,7 +94,7 @@ def _finish_pipeline(self, data):
)
if not created:
- ident.update(data=identity['data'], scopes=identity['scopes'])
+ identity_model.update(data=identity['data'], scopes=identity['scopes'])
except IntegrityError:
# If the external_id is already used for a different user or
# the user already has a different external_id remove those
@@ -104,13 +102,22 @@ def _finish_pipeline(self, data):
lookup = Q(external_id=identity['external_id']) | Q(user=self.request.user)
Identity.objects.filter(lookup, idp=idp).delete()
- Identity.objects.create(
+ identity_model = Identity.objects.create(
idp=idp,
user=self.request.user,
external_id=identity['external_id'],
**identity_data
)
+ org_integration_args = {}
+
+ if self.provider.needs_default_identity:
+ if not (identity and identity_model):
+ raise NotImplementedError('Integration requires an identity')
+ org_integration_args = {'default_auth_id': identity_model.id}
+
+ org_integration = integration.add_organization(self.organization.id, **org_integration_args)
+
return self._dialog_response(serialize(org_integration, self.request.user), True)
def _dialog_response(self, data, success):
diff --git a/src/sentry/integrations/vsts/integration.py b/src/sentry/integrations/vsts/integration.py
index ff52d61fe11f03..112db55b759702 100644
--- a/src/sentry/integrations/vsts/integration.py
+++ b/src/sentry/integrations/vsts/integration.py
@@ -72,6 +72,7 @@ class VSTSIntegrationProvider(IntegrationProvider):
metadata = metadata
domain = '.visualstudio.com'
api_version = '4.1'
+ needs_default_identity = True
setup_dialog_config = {
'width': 600,
diff --git a/tests/sentry/integrations/test_pipeline.py b/tests/sentry/integrations/test_pipeline.py
index b4f59d2ff7b2b0..7c98228ef2e92f 100644
--- a/tests/sentry/integrations/test_pipeline.py
+++ b/tests/sentry/integrations/test_pipeline.py
@@ -1,6 +1,6 @@
from __future__ import absolute_import
-from sentry.models import Integration, OrganizationIntegration
+from sentry.models import Identity, Integration, OrganizationIntegration
from sentry.testutils import IntegrationTestCase
from sentry.integrations.example import ExampleIntegrationProvider
@@ -13,9 +13,11 @@ def setUp(self):
self.original_build_integration = self.provider.build_integration
self.provider.build_integration = lambda self, data: data
self.external_id = 'dummy_id-123'
+ self.provider.needs_default_identity = False
def tearDown(self):
self.provider.build_integration = self.original_build_integration
+ self.provider.needs_default_identity = False
def test_with_data(self):
data = {
@@ -88,3 +90,84 @@ def test_expect_exists_does_not_update(self):
organization_id=self.organization.id,
integration_id=integration.id,
).exists()
+
+ def test_with_default_id(self):
+ self.provider.needs_default_identity = True
+ data = {
+ 'external_id': self.external_id,
+ 'name': 'Name',
+ 'metadata': {'url': 'https://example.com'},
+ 'user_identity': {
+ 'type': 'plugin',
+ 'external_id': 'AccountId',
+ 'scopes': [],
+ 'data': {
+ 'access_token': 'token12345',
+ 'expires_in': '123456789',
+ 'refresh_token': 'refresh12345',
+ 'token_type': 'typetype',
+ },
+ }
+ }
+ self.pipeline.state.data = data
+ resp = self.pipeline.finish_pipeline()
+
+ self.assertDialogSuccess(resp)
+
+ integration = Integration.objects.get(
+ provider=self.provider.key,
+ external_id=self.external_id,
+ )
+ org_integration = OrganizationIntegration.objects.get(
+ organization_id=self.organization.id,
+ integration_id=integration.id,
+ )
+ assert org_integration.default_auth_id is not None
+ assert Identity.objects.filter(id=org_integration.default_auth_id).exists()
+
+ def test_default_identity_does_not_update(self):
+ self.provider.needs_default_identity = True
+ old_identity_id = 234567
+ integration = Integration.objects.create(
+ provider=self.provider.key,
+ external_id=self.external_id,
+ metadata={
+ 'url': 'https://example.com',
+ },
+ )
+ OrganizationIntegration.objects.create(
+ organization=self.organization,
+ integration=integration,
+ default_auth_id=old_identity_id,
+ )
+ self.pipeline.state.data = {
+ 'external_id': self.external_id,
+ 'name': 'Name',
+ 'metadata': {'url': 'https://example.com'},
+ 'user_identity': {
+ 'type': 'plugin',
+ 'external_id': 'AccountId',
+ 'scopes': [],
+ 'data': {
+ 'access_token': 'token12345',
+ 'expires_in': '123456789',
+ 'refresh_token': 'refresh12345',
+ 'token_type': 'typetype',
+ },
+ }
+ }
+
+ resp = self.pipeline.finish_pipeline()
+ self.assertDialogSuccess(resp)
+
+ integration = Integration.objects.get(
+ provider=self.provider.key,
+ external_id=self.external_id,
+ )
+
+ org_integration = OrganizationIntegration.objects.get(
+ organization_id=self.organization.id,
+ integration_id=integration.id,
+ )
+ assert org_integration.default_auth_id == old_identity_id
+ assert Identity.objects.filter(external_id='AccountId').exists()
|
e85ea8812899dd8a8017712741065bb0d57329e8
|
2021-03-27 00:51:41
|
Kelly Carino
|
fix(metric_alerts): Fix Slack timestamp footer (#24733)
| false
|
Fix Slack timestamp footer (#24733)
|
fix
|
diff --git a/src/sentry/integrations/slack/utils.py b/src/sentry/integrations/slack/utils.py
index 221970dbbaa4e6..d93d86c30dbec4 100644
--- a/src/sentry/integrations/slack/utils.py
+++ b/src/sentry/integrations/slack/utils.py
@@ -326,6 +326,12 @@ def build_incident_attachment(action, incident, metric_value=None, method=None):
"Critical": LEVEL_TO_COLOR["fatal"],
}
+ incident_footer_ts = (
+ "<!date^{:.0f}^Sentry Incident - Started {} at {} | Sentry Incident>".format(
+ to_timestamp(data["ts"]), "{date_pretty}", "{time}"
+ )
+ )
+
return {
"fallback": data["title"],
"title": data["title"],
@@ -334,8 +340,7 @@ def build_incident_attachment(action, incident, metric_value=None, method=None):
"fields": [],
"mrkdwn_in": ["text"],
"footer_icon": data["logo_url"],
- "footer": "Sentry Incident",
- "ts": to_timestamp(data["ts"]),
+ "footer": incident_footer_ts,
"color": colors[data["status"]],
"actions": [],
}
diff --git a/tests/sentry/integrations/slack/test_utils.py b/tests/sentry/integrations/slack/test_utils.py
index ce4dd1423eafed..08d2ead4f60ac6 100644
--- a/tests/sentry/integrations/slack/test_utils.py
+++ b/tests/sentry/integrations/slack/test_utils.py
@@ -104,6 +104,11 @@ def test_simple(self):
alert_rule_trigger=trigger, triggered_for_incident=incident
)
title = f"Resolved: {alert_rule.name}"
+ incident_footer_ts = (
+ "<!date^{:.0f}^Sentry Incident - Started {} at {} | Sentry Incident>".format(
+ to_timestamp(incident.date_started), "{date_pretty}", "{time}"
+ )
+ )
assert build_incident_attachment(action, incident) == {
"fallback": title,
"title": title,
@@ -120,8 +125,7 @@ def test_simple(self):
"fields": [],
"mrkdwn_in": ["text"],
"footer_icon": logo_url,
- "footer": "Sentry Incident",
- "ts": to_timestamp(incident.date_started),
+ "footer": incident_footer_ts,
"color": RESOLVED_COLOR,
"actions": [],
}
@@ -136,6 +140,11 @@ def test_metric_value(self):
action = self.create_alert_rule_trigger_action(
alert_rule_trigger=trigger, triggered_for_incident=incident
)
+ incident_footer_ts = (
+ "<!date^{:.0f}^Sentry Incident - Started {} at {} | Sentry Incident>".format(
+ to_timestamp(incident.date_started), "{date_pretty}", "{time}"
+ )
+ )
# This should fail because it pulls status from `action` instead of `incident`
assert build_incident_attachment(
action, incident, metric_value=metric_value, method="fire"
@@ -155,8 +164,7 @@ def test_metric_value(self):
"fields": [],
"mrkdwn_in": ["text"],
"footer_icon": logo_url,
- "footer": "Sentry Incident",
- "ts": to_timestamp(incident.date_started),
+ "footer": incident_footer_ts,
"color": LEVEL_TO_COLOR["fatal"],
"actions": [],
}
|
bef4528b7f5061949d5df11df9458abdf6c03854
|
2022-06-29 19:59:39
|
anthony sottile
|
ref: upgrade simplejson so it gets a prebuilt wheel on M1 (#36124)
| false
|
upgrade simplejson so it gets a prebuilt wheel on M1 (#36124)
|
ref
|
diff --git a/requirements-base.txt b/requirements-base.txt
index 13ff8fdde15983..b8662226fd9e3f 100644
--- a/requirements-base.txt
+++ b/requirements-base.txt
@@ -58,7 +58,7 @@ sentry-arroyo==0.2.0
sentry-relay==0.8.12
sentry-sdk>=1.4.3,<1.6.0
snuba-sdk==1.0.0
-simplejson==3.17.2
+simplejson==3.17.6
statsd==3.3
structlog==21.1.0
symbolic==8.7.1
|
c11ee49d5437a69058b47c21f70234ef8aa30642
|
2023-07-15 00:51:16
|
Colleen O'Rourke
|
ref(sort): Remove priority and betterpriority flags (#52770)
| false
|
Remove priority and betterpriority flags (#52770)
|
ref
|
diff --git a/src/sentry/api/endpoints/organization_group_index.py b/src/sentry/api/endpoints/organization_group_index.py
index 25c047d642f6d6..2a46779d4819c9 100644
--- a/src/sentry/api/endpoints/organization_group_index.py
+++ b/src/sentry/api/endpoints/organization_group_index.py
@@ -1,6 +1,6 @@
import functools
from datetime import datetime, timedelta
-from typing import Any, List, Mapping, Optional, Sequence, Type, TypeVar
+from typing import Any, List, Mapping, Optional, Sequence
from django.utils import timezone
from rest_framework.exceptions import ParseError, PermissionDenied
@@ -38,11 +38,7 @@
)
from sentry.search.events.constants import EQUALITY_OPERATORS
from sentry.search.snuba.backend import assigned_or_suggested_filter
-from sentry.search.snuba.executors import (
- DEFAULT_PRIORITY_WEIGHTS,
- PrioritySortWeights,
- get_search_filter,
-)
+from sentry.search.snuba.executors import get_search_filter
from sentry.snuba import discover
from sentry.types.ratelimit import RateLimit, RateLimitCategory
from sentry.utils.cursors import Cursor, CursorResult
@@ -164,57 +160,6 @@ class OrganizationGroupIndexEndpoint(OrganizationEventsEndpointBase):
},
}
- @staticmethod
- def build_better_priority_sort_kwargs(request: Request) -> Mapping[str, PrioritySortWeights]:
- """
- Temporary function to be used while developing the new priority sort. Parses the query params in the request.
-
- :param logLevel: the weight (number from 0 to 10) to apply for events
- :param hasStacktrace: the weight (number from 0 to 3) to apply for error events with stacktraces or not
- :param eventHalflifeHours: each multiple of eventHalflifeHours halves the contribution score of an event
- :param v2: boolean to switch between using v1 or v2 priority sort
- :param norm: boolean to switch between normalizing the individual contribution scores to [0, 1] or not
- """
-
- R = TypeVar("R")
-
- def _coerce(val: Optional[str], func: Type[R], default: R) -> R:
- if func == bool:
- func = lambda x: str(x).lower() == "true"
-
- return func(val) if val is not None else default
-
- # XXX(CEO): these default values are based on sort E
- return {
- "better_priority": {
- "log_level": _coerce(
- request.GET.get("logLevel"), int, DEFAULT_PRIORITY_WEIGHTS["log_level"]
- ),
- "has_stacktrace": _coerce(
- request.GET.get("hasStacktrace"),
- int,
- DEFAULT_PRIORITY_WEIGHTS["has_stacktrace"],
- ),
- "relative_volume": _coerce(
- request.GET.get("relativeVolume"),
- int,
- DEFAULT_PRIORITY_WEIGHTS["relative_volume"],
- ),
- "event_halflife_hours": _coerce(
- request.GET.get("eventHalflifeHours"),
- int,
- DEFAULT_PRIORITY_WEIGHTS["event_halflife_hours"],
- ),
- "issue_halflife_hours": _coerce(
- request.GET.get("issueHalflifeHours"),
- int,
- DEFAULT_PRIORITY_WEIGHTS["issue_halflife_hours"],
- ),
- "v2": _coerce(request.GET.get("v2"), bool, DEFAULT_PRIORITY_WEIGHTS["v2"]),
- "norm": _coerce(request.GET.get("norm"), bool, DEFAULT_PRIORITY_WEIGHTS["norm"]),
- }
- }
-
def _search(
self, request: Request, organization, projects, environments, extra_query_kwargs=None
):
@@ -226,9 +171,6 @@ def _search(
assert "environment" not in extra_query_kwargs
query_kwargs.update(extra_query_kwargs)
- if query_kwargs["sort_by"] == "betterPriority":
- query_kwargs["aggregate_kwargs"] = self.build_better_priority_sort_kwargs(request)
-
query_kwargs["environments"] = environments if environments else None
query_kwargs["actor"] = request.user
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index f110518b7bb343..2f25e45707970a 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -1481,8 +1481,6 @@ def SOCIAL_AUTH_DEFAULT_USERNAME() -> str:
"organizations:issue-details-replay-event": False,
# Enable sorting Issue detail events by 'most helpful'
"organizations:issue-details-most-helpful-event": False,
- # Enable better priority sort algorithm.
- "organizations:issue-list-better-priority-sort": False,
# Adds the ttid & ttfd vitals to the frontend
"organizations:mobile-vitals": False,
# Display CPU and memory metrics in transactions with profiles
diff --git a/src/sentry/features/__init__.py b/src/sentry/features/__init__.py
index 6c49928b8bd66e..58ccf24ff0f18f 100644
--- a/src/sentry/features/__init__.py
+++ b/src/sentry/features/__init__.py
@@ -92,7 +92,6 @@
default_manager.add("organizations:issue-details-replay-event", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:issue-details-most-helpful-event", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:issue-details-tag-improvements", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
-default_manager.add("organizations:issue-list-better-priority-sort", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:issue-platform", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:issue-search-allow-postgres-only-search", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
default_manager.add("organizations:issue-search-use-cdc-primary", OrganizationFeature, FeatureHandlerStrategy.REMOTE)
diff --git a/src/sentry/search/snuba/executors.py b/src/sentry/search/snuba/executors.py
index e4a42b3362ad84..78bac15f0cf12e 100644
--- a/src/sentry/search/snuba/executors.py
+++ b/src/sentry/search/snuba/executors.py
@@ -249,7 +249,7 @@ def _prepare_aggregations(
aggregations = []
for alias in required_aggregations:
aggregation = self.aggregation_defs[alias]
- if replace_better_priority_aggregation and alias == "better_priority":
+ if replace_better_priority_aggregation and alias in ["priority", "better_priority"]:
aggregation = self.aggregation_defs["better_priority_issue_platform"]
if callable(aggregation):
if aggregate_kwargs:
@@ -303,9 +303,8 @@ def _prepare_params_for_category(
conditions.append(converted_filter)
if (
- sort_field == "better_priority"
+ sort_field in ["priority", "better_priority"]
and group_category is not GroupCategory.ERROR.value
- and features.has("organizations:issue-list-better-priority-sort", organization)
):
aggregations = self._prepare_aggregations(
sort_field, start, end, having, aggregate_kwargs, True
@@ -696,7 +695,7 @@ class PostgresSnubaQueryExecutor(AbstractQueryExecutor):
"date": "last_seen",
"freq": "times_seen",
"new": "first_seen",
- "priority": "priority",
+ "priority": "better_priority",
"user": "user_count",
# We don't need a corresponding snuba field here, since this sort only happens
# in Postgres
@@ -708,8 +707,7 @@ class PostgresSnubaQueryExecutor(AbstractQueryExecutor):
"times_seen": ["count()", ""],
"first_seen": ["multiply(toUInt64(min(timestamp)), 1000)", ""],
"last_seen": ["multiply(toUInt64(max(timestamp)), 1000)", ""],
- # https://github.com/getsentry/sentry/blob/804c85100d0003cfdda91701911f21ed5f66f67c/src/sentry/event_manager.py#L241-L271
- "priority": ["toUInt64(plus(multiply(log(times_seen), 600), last_seen))", ""],
+ "priority": better_priority_aggregation,
# Only makes sense with WITH TOTALS, returns 1 for an individual group.
"total": ["uniq", ISSUE_FIELD_NAME],
"user_count": ["uniq", "tags[sentry:user]"],
diff --git a/tests/snuba/api/endpoints/test_organization_group_index.py b/tests/snuba/api/endpoints/test_organization_group_index.py
index 39f7449bf02bf3..5dce9d0763f586 100644
--- a/tests/snuba/api/endpoints/test_organization_group_index.py
+++ b/tests/snuba/api/endpoints/test_organization_group_index.py
@@ -114,7 +114,6 @@ def test_query_for_archived(self):
assert len(response.data) == 1
assert response.data[0]["id"] == str(group.id)
- @with_feature("organizations:issue-list-better-priority-sort")
def test_sort_by_better_priority(self):
group = self.store_event(
data={
diff --git a/tests/snuba/search/test_backend.py b/tests/snuba/search/test_backend.py
index c0172fb6a1d0e8..8a3777aab62926 100644
--- a/tests/snuba/search/test_backend.py
+++ b/tests/snuba/search/test_backend.py
@@ -359,26 +359,25 @@ def test_sort(self):
assert list(results) == [self.group1, self.group2]
results = self.make_query(sort_by="priority")
- assert list(results) == [self.group1, self.group2]
+ assert list(results) == [self.group2, self.group1]
results = self.make_query(sort_by="user")
assert list(results) == [self.group1, self.group2]
def test_better_priority_sort(self):
- with self.feature("organizations:issue-list-better-priority-sort"):
- weights: PrioritySortWeights = {
- "log_level": 5,
- "has_stacktrace": 5,
- "relative_volume": 1,
- "event_halflife_hours": 4,
- "issue_halflife_hours": 24 * 7,
- "v2": False,
- "norm": False,
- }
- results = self.make_query(
- sort_by="betterPriority",
- aggregate_kwargs=weights,
- )
+ weights: PrioritySortWeights = {
+ "log_level": 5,
+ "has_stacktrace": 5,
+ "relative_volume": 1,
+ "event_halflife_hours": 4,
+ "issue_halflife_hours": 24 * 7,
+ "v2": False,
+ "norm": False,
+ }
+ results = self.make_query(
+ sort_by="betterPriority",
+ aggregate_kwargs=weights,
+ )
assert list(results) == [self.group2, self.group1]
def test_sort_with_environment(self):
@@ -661,7 +660,7 @@ def test_search_filter_query_with_custom_priority_tag_and_priority_sort(self):
project_id=self.project.id,
)
results = self.make_query(search_filter_query="priority:%s" % priority, sort_by="priority")
- assert list(results) == [self.group1, self.group2]
+ assert list(results) == [self.group2, self.group1]
def test_search_tag_overlapping_with_internal_fields(self):
# Using a tag of email overlaps with the promoted user.email column in events.
@@ -2283,7 +2282,11 @@ def test_sort_multi_project(self):
assert list(results) == [self.group1, self.group_p2, self.group2]
results = self.make_query([self.project, self.project2], sort_by="priority")
- assert list(results) == [self.group1, self.group2, self.group_p2]
+ assert list(results) == [
+ self.group_p2,
+ self.group2,
+ self.group1,
+ ]
results = self.make_query([self.project, self.project2], sort_by="user")
assert list(results) == [self.group1, self.group2, self.group_p2]
@@ -2631,21 +2634,20 @@ def test_better_priority_sort_old_and_new_events(self):
# datetime(2017, 9, 6, 0, 0)
old_event.data["timestamp"] = 1504656000.0
- with self.feature("organizations:issue-list-better-priority-sort"):
- weights: PrioritySortWeights = {
- "log_level": 0,
- "has_stacktrace": 0,
- "relative_volume": 1,
- "event_halflife_hours": 4,
- "issue_halflife_hours": 24 * 7,
- "v2": False,
- "norm": False,
- }
- results = self.make_query(
- sort_by="betterPriority",
- projects=[new_project],
- aggregate_kwargs=weights,
- )
+ weights: PrioritySortWeights = {
+ "log_level": 0,
+ "has_stacktrace": 0,
+ "relative_volume": 1,
+ "event_halflife_hours": 4,
+ "issue_halflife_hours": 24 * 7,
+ "v2": False,
+ "norm": False,
+ }
+ results = self.make_query(
+ sort_by="betterPriority",
+ projects=[new_project],
+ aggregate_kwargs=weights,
+ )
recent_group = Group.objects.get(id=recent_event.group.id)
old_group = Group.objects.get(id=old_event.group.id)
assert list(results) == [recent_group, old_group]
@@ -2682,21 +2684,20 @@ def test_better_priority_sort_v2(self):
# datetime(2017, 9, 6, 0, 0)
old_event.data["timestamp"] = 1504656000.0
- with self.feature("organizations:issue-list-better-priority-sort"):
- weights: PrioritySortWeights = {
- "log_level": 0,
- "has_stacktrace": 0,
- "relative_volume": 1,
- "event_halflife_hours": 4,
- "issue_halflife_hours": 24 * 7,
- "v2": True,
- "norm": False,
- }
- results = self.make_query(
- sort_by="betterPriority",
- projects=[new_project],
- aggregate_kwargs=weights,
- )
+ weights: PrioritySortWeights = {
+ "log_level": 0,
+ "has_stacktrace": 0,
+ "relative_volume": 1,
+ "event_halflife_hours": 4,
+ "issue_halflife_hours": 24 * 7,
+ "v2": True,
+ "norm": False,
+ }
+ results = self.make_query(
+ sort_by="betterPriority",
+ projects=[new_project],
+ aggregate_kwargs=weights,
+ )
recent_group = Group.objects.get(id=recent_event.group.id)
old_group = Group.objects.get(id=old_event.group.id)
assert list(results) == [recent_group, old_group]
@@ -2981,7 +2982,6 @@ def test_better_priority_mixed_group_types(self):
[
"organizations:issue-platform",
ProfileFileIOGroupType.build_visible_feature_name(),
- "organizations:issue-list-better-priority-sort",
]
):
results = query_executor.snuba_search(
|
2140213e7d42795c112227b4f0914fe9fa55e34b
|
2024-04-26 23:20:18
|
Katie Byers
|
chore(seer grouping): Add seer grouping metadata flag (#69787)
| false
|
Add seer grouping metadata flag (#69787)
|
chore
|
diff --git a/src/sentry/conf/server.py b/src/sentry/conf/server.py
index 3ca0d3e30ce612..f76cccc75ed735 100644
--- a/src/sentry/conf/server.py
+++ b/src/sentry/conf/server.py
@@ -2005,6 +2005,8 @@ def custom_parameter_sort(parameter: dict) -> tuple[str, int]:
"projects:similarity-embeddings": False,
# Enable similarity embeddings grouping
"projects:similarity-embeddings-grouping": False,
+ # Enable adding seer grouping metadata to new groups
+ "projects:similarity-embeddings-metadata": False,
# Starfish: extract metrics from the spans
"projects:span-metrics-extraction": False,
"projects:span-metrics-extraction-ga-modules": False,
diff --git a/src/sentry/features/temporary.py b/src/sentry/features/temporary.py
index bd9464ed88bfc3..12ce50273d70d7 100644
--- a/src/sentry/features/temporary.py
+++ b/src/sentry/features/temporary.py
@@ -276,6 +276,7 @@ def register_temporary_features(manager: FeatureManager):
manager.add("projects:race-free-group-creation", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
manager.add("projects:similarity-embeddings", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
manager.add("projects:similarity-embeddings-grouping", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
+ manager.add("projects:similarity-embeddings-metadata", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
manager.add("projects:similarity-indexing", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
manager.add("projects:similarity-view", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
manager.add("projects:span-metrics-extraction", ProjectFeature, FeatureHandlerStrategy.INTERNAL)
|
a6b4d5421a5b8e1c0e12d5d34fae46c944ae1b7e
|
2019-05-28 15:39:31
|
Markus Unterwaditzer
|
fix(minidumps): Restore error messages for missing dsyms (#13417)
| false
|
Restore error messages for missing dsyms (#13417)
|
fix
|
diff --git a/src/sentry/lang/native/minidump.py b/src/sentry/lang/native/minidump.py
index 38c20a5c8ce311..eebfe030861ac1 100644
--- a/src/sentry/lang/native/minidump.py
+++ b/src/sentry/lang/native/minidump.py
@@ -126,8 +126,6 @@ def merge_symbolicator_minidump_system_info(data, system_info):
def merge_symbolicator_minidump_response(data, response):
- sdk_info = get_sdk_from_event(data)
-
data['platform'] = 'native'
if response.get('crashed') is not None:
data['level'] = 'fatal' if response['crashed'] else 'info'
@@ -137,6 +135,8 @@ def merge_symbolicator_minidump_response(data, response):
if response.get('system_info'):
merge_symbolicator_minidump_system_info(data, response['system_info'])
+ sdk_info = get_sdk_from_event(data)
+
images = []
set_path(data, 'debug_meta', 'images', value=images)
diff --git a/tests/symbolicator/snapshots/SymbolicatorMinidumpIntegrationTest/test_missing_dsym.pysnap b/tests/symbolicator/snapshots/SymbolicatorMinidumpIntegrationTest/test_missing_dsym.pysnap
new file mode 100644
index 00000000000000..23461afcc1b8ea
--- /dev/null
+++ b/tests/symbolicator/snapshots/SymbolicatorMinidumpIntegrationTest/test_missing_dsym.pysnap
@@ -0,0 +1,477 @@
+---
+created: '2019-05-28T09:16:05.541318Z'
+creator: sentry
+source: tests/symbolicator/test_minidump_full.py
+---
+contexts:
+ device:
+ arch: x86
+ type: device
+ os:
+ build: ''
+ name: Windows
+ type: os
+ version: 10.0.14393
+debug_meta:
+ images:
+ - code_file: C:\projects\breakpad-tools\windows\Release\crash.exe
+ code_id: 5ab380779000
+ debug_file: C:\projects\breakpad-tools\windows\Release\crash.pdb
+ debug_id: 3249d99d-0c40-4931-8610-f4e4fb0b6936-1
+ image_addr: '0x2a0000'
+ image_size: 36864
+ type: pe
+ - code_file: C:\Windows\System32\dbghelp.dll
+ code_id: 57898e12145000
+ debug_file: dbghelp.pdb
+ debug_id: 9c2a902b-6fdf-40ad-8308-588a41d572a0-1
+ image_addr: '0x70850000'
+ image_size: 1331200
+ type: pe
+ - code_file: C:\Windows\System32\msvcp140.dll
+ code_id: 589abc846c000
+ debug_file: msvcp140.i386.pdb
+ debug_id: bf5257f7-8c26-43dd-9bb7-901625e1136a-1
+ image_addr: '0x709a0000'
+ image_size: 442368
+ type: pe
+ - code_file: C:\Windows\System32\apphelp.dll
+ code_id: 57898eeb92000
+ debug_file: apphelp.pdb
+ debug_id: 8daf7773-372f-460a-af38-944e193f7e33-1
+ image_addr: '0x70a10000'
+ image_size: 598016
+ type: pe
+ - code_file: C:\Windows\System32\dbgcore.dll
+ code_id: 57898dab25000
+ debug_file: dbgcore.pdb
+ debug_id: aec7ef2f-df4b-4642-a471-4c3e5fe8760a-1
+ image_addr: '0x70b70000'
+ image_size: 151552
+ type: pe
+ - code_file: C:\Windows\System32\VCRUNTIME140.dll
+ code_id: 589abc7714000
+ debug_file: vcruntime140.i386.pdb
+ debug_id: 0ed80a50-ecda-472b-86a4-eb6c833f8e1b-1
+ image_addr: '0x70c60000'
+ image_size: 81920
+ type: pe
+ - code_file: C:\Windows\System32\CRYPTBASE.dll
+ code_id: 57899141a000
+ debug_file: cryptbase.pdb
+ debug_id: 147c51fb-7ca1-408f-85b5-285f2ad6f9c5-1
+ image_addr: '0x73ba0000'
+ image_size: 40960
+ type: pe
+ - code_file: C:\Windows\System32\sspicli.dll
+ code_id: 59bf30e31f000
+ debug_file: wsspicli.pdb
+ debug_id: 51e432b1-0450-4b19-8ed1-6d4335f9f543-1
+ image_addr: '0x73bb0000'
+ image_size: 126976
+ type: pe
+ - code_file: C:\Windows\System32\advapi32.dll
+ code_id: 5a49bb7677000
+ debug_file: advapi32.pdb
+ debug_id: 0c799483-b549-417d-8433-4331852031fe-1
+ image_addr: '0x73c70000'
+ image_size: 487424
+ type: pe
+ - code_file: C:\Windows\System32\msvcrt.dll
+ code_id: 57899155be000
+ debug_file: msvcrt.pdb
+ debug_id: 6f6409b3-d520-43c7-9b2f-62e00bfe761c-1
+ image_addr: '0x73cf0000'
+ image_size: 778240
+ type: pe
+ - code_file: C:\Windows\System32\sechost.dll
+ code_id: 598942c741000
+ debug_file: sechost.pdb
+ debug_id: 6f6a05dd-0a80-478b-a419-9b88703bf75b-1
+ image_addr: '0x74450000'
+ image_size: 266240
+ type: pe
+ - code_file: C:\Windows\System32\kernel32.dll
+ code_id: 590285e9e0000
+ debug_file: wkernel32.pdb
+ debug_id: d3474559-96f7-47d6-bf43-c176b2171e68-1
+ image_addr: '0x75050000'
+ image_size: 917504
+ type: pe
+ - code_file: C:\Windows\System32\bcryptPrimitives.dll
+ code_id: 59b0df8f5a000
+ debug_file: bcryptprimitives.pdb
+ debug_id: 287b19c3-9209-4a2b-bb8f-bcc37f411b11-1
+ image_addr: '0x75130000'
+ image_size: 368640
+ type: pe
+ - code_file: C:\Windows\System32\rpcrt4.dll
+ code_id: 5a49bb75c1000
+ debug_file: wrpcrt4.pdb
+ debug_id: ae131c67-27a7-4fa1-9916-b5a4aef41190-1
+ image_addr: '0x75810000'
+ image_size: 790528
+ type: pe
+ - code_file: C:\Windows\System32\ucrtbase.dll
+ code_id: 59bf2b5ae0000
+ debug_file: ucrtbase.pdb
+ debug_id: 6bedcbce-0a3a-40e9-8040-81c2c8c6cc2f-1
+ image_addr: '0x758f0000'
+ image_size: 917504
+ type: pe
+ - code_file: C:\Windows\System32\KERNELBASE.dll
+ code_id: 59bf2bcf1a1000
+ debug_file: wkernelbase.pdb
+ debug_id: 8462294a-c645-402d-ac82-a4e95f61ddf9-1
+ image_addr: '0x76db0000'
+ image_size: 1708032
+ type: pe
+ - code_file: C:\Windows\System32\ntdll.dll
+ code_id: 59b0d8f3183000
+ debug_file: wntdll.pdb
+ debug_id: 971f98e5-ce60-41ff-b2d7-235bbeb34578-1
+ image_addr: '0x77170000'
+ image_size: 1585152
+ type: pe
+errors:
+- name: timestamp
+ type: past_timestamp
+ value: 1521713273
+- image_path: C:\projects\breakpad-tools\windows\Release\crash.exe
+ image_uuid: 3249d99d-0c40-4931-8610-f4e4fb0b6936-1
+ message: None
+ type: native_missing_dsym
+exception:
+ values:
+ - mechanism:
+ handled: false
+ synthetic: true
+ type: minidump
+ raw_stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a2d97'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a3435'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x7584e9c0'
+ package: C:\Windows\System32\rpcrt4.dll
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x75810000'
+ package: C:\Windows\System32\rpcrt4.dll
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x70b7ae40'
+ package: C:\Windows\System32\dbgcore.dll
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x70850000'
+ package: C:\Windows\System32\dbghelp.dll
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x7584e9c0'
+ package: C:\Windows\System32\rpcrt4.dll
+ trust: scan
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a28d0'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a2a3d'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x10ff670'
+ ebx: '0xfe5000'
+ ecx: '0x10ff670'
+ edi: '0x13bfd78'
+ edx: '0x7'
+ eflags: '0x10246'
+ eip: '0x2a2a3d'
+ esi: '0x759c6314'
+ esp: '0x10ff644'
+ stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a28d0'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x2a2a3d'
+ package: C:\projects\breakpad-tools\windows\Release\crash.exe
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x10ff670'
+ ebx: '0xfe5000'
+ ecx: '0x10ff670'
+ edi: '0x13bfd78'
+ edx: '0x7'
+ eflags: '0x10246'
+ eip: '0x2a2a3d'
+ esi: '0x759c6314'
+ esp: '0x10ff644'
+ thread_id: 1636
+ type: EXCEPTION_ACCESS_VIOLATION_WRITE
+ value: 'Fatal Error: EXCEPTION_ACCESS_VIOLATION_WRITE'
+stacktrace: null
+threads:
+ values:
+ - crashed: true
+ id: 1636
+ - crashed: false
+ id: 3580
+ raw_stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771e016c'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x159faa4'
+ ebx: '0x13b0990'
+ ecx: '0x0'
+ edi: '0x13b4af0'
+ edx: '0x0'
+ eflags: '0x216'
+ eip: '0x771e016c'
+ esi: '0x13b4930'
+ esp: '0x159f900'
+ stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771e016c'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x159faa4'
+ ebx: '0x13b0990'
+ ecx: '0x0'
+ edi: '0x13b4af0'
+ edx: '0x0'
+ eflags: '0x216'
+ eip: '0x771e016c'
+ esi: '0x13b4930'
+ esp: '0x159f900'
+ - crashed: false
+ id: 2600
+ raw_stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771e016c'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x169fb98'
+ ebx: '0x13b0990'
+ ecx: '0x0'
+ edi: '0x13b7c28'
+ edx: '0x0'
+ eflags: '0x202'
+ eip: '0x771e016c'
+ esi: '0x13b7a68'
+ esp: '0x169f9f4'
+ stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f44'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771d0f79'
+ package: C:\Windows\System32\ntdll.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x750662c4'
+ package: C:\Windows\System32\kernel32.dll
+ trust: fp
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771e016c'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x169fb98'
+ ebx: '0x13b0990'
+ ecx: '0x0'
+ edi: '0x13b7c28'
+ edx: '0x0'
+ eflags: '0x202'
+ eip: '0x771e016c'
+ esi: '0x13b7a68'
+ esp: '0x169f9f4'
+ - crashed: false
+ id: 2920
+ raw_stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771df3dc'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x179f2b8'
+ ebx: '0x17b1aa0'
+ ecx: '0x0'
+ edi: '0x17b1a90'
+ edx: '0x0'
+ eflags: '0x206'
+ eip: '0x771df3dc'
+ esi: '0x2cc'
+ esp: '0x179f2ac'
+ stacktrace:
+ frames:
+ - data:
+ symbolicator_status: missing
+ in_app: false
+ instruction_addr: '0x771df3dc'
+ package: C:\Windows\System32\ntdll.dll
+ trust: context
+ registers:
+ eax: '0x0'
+ ebp: '0x179f2b8'
+ ebx: '0x17b1aa0'
+ ecx: '0x0'
+ edi: '0x17b1a90'
+ edx: '0x0'
+ eflags: '0x206'
+ eip: '0x771df3dc'
+ esi: '0x2cc'
+ esp: '0x179f2ac'
diff --git a/tests/symbolicator/test_minidump_full.py b/tests/symbolicator/test_minidump_full.py
index 393c5ba01d9f5a..2647208f28d671 100644
--- a/tests/symbolicator/test_minidump_full.py
+++ b/tests/symbolicator/test_minidump_full.py
@@ -76,6 +76,18 @@ def test_full_minidump(self):
assert minidump.file.type == 'event.minidump'
assert minidump.file.checksum == '74bb01c850e8d65d3ffbc5bad5cabc4668fce247'
+ def test_missing_dsym(self):
+ with self.feature('organizations:event-attachments'):
+ with open(os.path.join(os.path.dirname(__file__), 'fixtures', 'windows.dmp'), 'rb') as f:
+ resp = self._postMinidumpWithHeader(f, {
+ 'sentry[logger]': 'test-logger',
+ })
+ assert resp.status_code == 200
+
+ event = Event.objects.get()
+ insta_snapshot_stacktrace_data(self, event.data)
+ assert not EventAttachment.objects.filter(event_id=event.event_id)
+
class SymbolicatorMinidumpIntegrationTest(MinidumpIntegrationTestBase, TransactionTestCase):
# For these tests to run, write `symbolicator.enabled: true` into your
|
6630c91cc9783c8970af21f96649dc3ab1f5af66
|
2023-01-11 02:50:29
|
Jonas
|
feat(profiling): offset space and handle negative time (#42809)
| false
|
offset space and handle negative time (#42809)
|
feat
|
diff --git a/static/app/components/profiling/flamegraph/flamegraph.tsx b/static/app/components/profiling/flamegraph/flamegraph.tsx
index b87fc174c12fa5..f8ea8bebd563fd 100644
--- a/static/app/components/profiling/flamegraph/flamegraph.tsx
+++ b/static/app/components/profiling/flamegraph/flamegraph.tsx
@@ -184,7 +184,7 @@ function Flamegraph(props: FlamegraphProps): ReactElement {
configSpaceTransform:
xAxis === 'transaction'
? new Rect(flamegraph.profile.startedAt, 0, 0, 0)
- : Rect.Empty(),
+ : undefined,
},
});
@@ -288,6 +288,11 @@ function Flamegraph(props: FlamegraphProps): ReactElement {
minWidth: spanChart.minSpanDuration,
barHeight: flamegraphTheme.SIZES.SPANS_BAR_HEIGHT,
depthOffset: flamegraphTheme.SIZES.SPANS_DEPTH_OFFSET,
+ configSpaceTransform:
+ // When a standalone axis is selected, the spans need to be relative to profile start time
+ xAxis === 'standalone'
+ ? new Rect(-flamegraph.profile.startedAt, 0, 0, 0)
+ : undefined,
},
});
@@ -296,9 +301,14 @@ function Flamegraph(props: FlamegraphProps): ReactElement {
return newView;
},
- // We skip position.view dependency because it will go into an infinite loop
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [spanChart, spansCanvas, flamegraphTheme.SIZES]
+ [
+ spanChart,
+ spansCanvas,
+ xAxis,
+ flamegraphView,
+ flamegraph.profile.startedAt,
+ flamegraphTheme.SIZES,
+ ]
);
// We want to make sure that the views have the same min zoom levels so that
diff --git a/static/app/components/profiling/flamegraph/flamegraphSpanTooltip.tsx b/static/app/components/profiling/flamegraph/flamegraphSpanTooltip.tsx
new file mode 100644
index 00000000000000..8a97e04a32a034
--- /dev/null
+++ b/static/app/components/profiling/flamegraph/flamegraphSpanTooltip.tsx
@@ -0,0 +1,85 @@
+import {useMemo} from 'react';
+import {vec2} from 'gl-matrix';
+
+import {BoundTooltip} from 'sentry/components/profiling/boundTooltip';
+import {t} from 'sentry/locale';
+import {CanvasView} from 'sentry/utils/profiling/canvasView';
+import {FlamegraphCanvas} from 'sentry/utils/profiling/flamegraphCanvas';
+import {formatColorForSpan, Rect} from 'sentry/utils/profiling/gl/utils';
+import {SpanChartRenderer2D} from 'sentry/utils/profiling/renderers/spansRenderer';
+import {SpanChart, SpanChartNode} from 'sentry/utils/profiling/spanChart';
+
+import {
+ FlamegraphTooltipColorIndicator,
+ FlamegraphTooltipFrameMainInfo,
+ FlamegraphTooltipTimelineInfo,
+} from './flamegraphTooltip';
+
+export function formatWeightToTransactionDuration(
+ span: SpanChartNode,
+ spanChart: SpanChart
+) {
+ return `(${Math.round((span.duration / spanChart.root.duration) * 100)}%)`;
+}
+
+export interface FlamegraphSpanTooltipProps {
+ canvasBounds: Rect;
+ configSpaceCursor: vec2;
+ hoveredNode: SpanChartNode;
+ spanChart: SpanChart;
+ spansCanvas: FlamegraphCanvas;
+ spansRenderer: SpanChartRenderer2D;
+ spansView: CanvasView<SpanChart>;
+}
+
+export function FlamegraphSpanTooltip({
+ canvasBounds,
+ configSpaceCursor,
+ spansCanvas,
+ spanChart,
+ spansView,
+ spansRenderer,
+ hoveredNode,
+}: FlamegraphSpanTooltipProps) {
+ const spanInConfigSpace = useMemo<Rect>(() => {
+ return new Rect(
+ hoveredNode.start,
+ hoveredNode.end,
+ hoveredNode.end - hoveredNode.start,
+ 1
+ ).transformRect(spansView.configSpaceTransform);
+ }, [spansView, hoveredNode]);
+
+ return (
+ <BoundTooltip
+ bounds={canvasBounds}
+ cursor={configSpaceCursor}
+ canvas={spansCanvas}
+ canvasView={spansView}
+ >
+ <FlamegraphTooltipFrameMainInfo>
+ <FlamegraphTooltipColorIndicator
+ backgroundImage={
+ hoveredNode.node.span.op === 'missing instrumentation'
+ ? `url(${spansRenderer.patternDataUrl})`
+ : 'none'
+ }
+ backgroundColor={formatColorForSpan(hoveredNode, spansRenderer)}
+ />
+ {spanChart.formatter(hoveredNode.duration)}{' '}
+ {formatWeightToTransactionDuration(hoveredNode, spanChart)}{' '}
+ {hoveredNode.node.span.description}
+ </FlamegraphTooltipFrameMainInfo>
+ <FlamegraphTooltipTimelineInfo>
+ {hoveredNode.node.span.op ? `${t('op')}:${hoveredNode.node.span.op} ` : null}
+ {hoveredNode.node.span.status
+ ? `${t('status')}:${hoveredNode.node.span.status}`
+ : null}
+ </FlamegraphTooltipTimelineInfo>
+ <FlamegraphTooltipTimelineInfo>
+ {spansRenderer.spanChart.timelineFormatter(spanInConfigSpace.left)} {' \u2014 '}
+ {spansRenderer.spanChart.timelineFormatter(spanInConfigSpace.right)}
+ </FlamegraphTooltipTimelineInfo>
+ </BoundTooltip>
+ );
+}
diff --git a/static/app/components/profiling/flamegraph/flamegraphSpans.tsx b/static/app/components/profiling/flamegraph/flamegraphSpans.tsx
index b47acd89b96869..0f6a847ec65ddd 100644
--- a/static/app/components/profiling/flamegraph/flamegraphSpans.tsx
+++ b/static/app/components/profiling/flamegraph/flamegraphSpans.tsx
@@ -12,7 +12,6 @@ import {vec2} from 'gl-matrix';
import * as qs from 'query-string';
import LoadingIndicator from 'sentry/components/loadingIndicator';
-import {BoundTooltip} from 'sentry/components/profiling/boundTooltip';
import {t} from 'sentry/locale';
import {
CanvasPoolManager,
@@ -22,7 +21,6 @@ import {CanvasView} from 'sentry/utils/profiling/canvasView';
import {useFlamegraphTheme} from 'sentry/utils/profiling/flamegraph/useFlamegraphTheme';
import {FlamegraphCanvas} from 'sentry/utils/profiling/flamegraphCanvas';
import {
- formatColorForSpan,
getConfigViewTranslationBetweenVectors,
getPhysicalSpacePositionFromOffset,
Rect,
@@ -39,18 +37,7 @@ import {useDrawHoveredBorderEffect} from './interactions/useDrawHoveredBorderEff
import {useDrawSelectedBorderEffect} from './interactions/useDrawSelectedBorderEffect';
import {useInteractionViewCheckPoint} from './interactions/useInteractionViewCheckPoint';
import {useWheelCenterZoom} from './interactions/useWheelCenterZoom';
-import {
- FlamegraphTooltipColorIndicator,
- FlamegraphTooltipFrameMainInfo,
- FlamegraphTooltipTimelineInfo,
-} from './flamegraphTooltip';
-
-export function formatWeightToTransactionDuration(
- span: SpanChartNode,
- spanChart: SpanChart
-) {
- return `(${Math.round((span.duration / spanChart.root.duration) * 100)}%)`;
-}
+import {FlamegraphSpanTooltip} from './flamegraphSpanTooltip';
interface FlamegraphSpansProps {
canvasBounds: Rect;
@@ -368,36 +355,15 @@ export function FlamegraphSpans({
<MessageContainer>{t('Transaction has no spans')}</MessageContainer>
) : null}
{hoveredNode && spansRenderer && configSpaceCursor && spansCanvas && spansView ? (
- <BoundTooltip
- bounds={canvasBounds}
- cursor={configSpaceCursor}
- canvas={spansCanvas}
- canvasView={spansView}
- >
- <FlamegraphTooltipFrameMainInfo>
- <FlamegraphTooltipColorIndicator
- backgroundImage={
- hoveredNode.node.span.op === 'missing instrumentation'
- ? `url(${spansRenderer.patternDataUrl})`
- : 'none'
- }
- backgroundColor={formatColorForSpan(hoveredNode, spansRenderer)}
- />
- {spanChart.formatter(hoveredNode.duration)}{' '}
- {formatWeightToTransactionDuration(hoveredNode, spanChart)}{' '}
- {hoveredNode.node.span.description}
- </FlamegraphTooltipFrameMainInfo>
- <FlamegraphTooltipTimelineInfo>
- {hoveredNode.node.span.op ? `${t('op')}:${hoveredNode.node.span.op} ` : null}
- {hoveredNode.node.span.status
- ? `${t('status')}:${hoveredNode.node.span.status}`
- : null}
- </FlamegraphTooltipTimelineInfo>
- <FlamegraphTooltipTimelineInfo>
- {spansRenderer.spanChart.timelineFormatter(hoveredNode.start)} {' \u2014 '}
- {spansRenderer.spanChart.timelineFormatter(hoveredNode.end)}
- </FlamegraphTooltipTimelineInfo>
- </BoundTooltip>
+ <FlamegraphSpanTooltip
+ spanChart={spanChart}
+ configSpaceCursor={configSpaceCursor}
+ spansCanvas={spansCanvas}
+ spansView={spansView}
+ spansRenderer={spansRenderer}
+ hoveredNode={hoveredNode}
+ canvasBounds={canvasBounds}
+ />
) : null}
</Fragment>
);
diff --git a/static/app/utils/profiling/units/unit.spec.ts b/static/app/utils/profiling/units/unit.spec.ts
index e23891f49a677e..9153a2bdd6ef50 100644
--- a/static/app/utils/profiling/units/unit.spec.ts
+++ b/static/app/utils/profiling/units/unit.spec.ts
@@ -4,22 +4,27 @@ describe('makeTimelineFormatter', () => {
it('handles base', () => {
const formatter = makeTimelineFormatter('seconds');
expect(formatter(61)).toBe('01:01.000');
+ expect(formatter(-61)).toBe('-01:01.000');
});
it('formats s', () => {
const formatter = makeTimelineFormatter('seconds');
expect(formatter(1)).toBe('00:01.000');
expect(formatter(12)).toBe('00:12.000');
+ expect(formatter(-1)).toBe('-00:01.000');
+ expect(formatter(-12)).toBe('-00:12.000');
});
it('formats ms', () => {
const formatter = makeTimelineFormatter('seconds');
expect(formatter(1.543)).toBe('00:01.543');
+ expect(formatter(-1.543)).toBe('-00:01.543');
});
it('doesnt overflow template', () => {
const formatter = makeTimelineFormatter('seconds');
expect(formatter(1.54355)).toBe('00:01.543');
+ expect(formatter(-1.54355)).toBe('-00:01.543');
});
});
diff --git a/static/app/utils/profiling/units/units.ts b/static/app/utils/profiling/units/units.ts
index dbf23c4264db63..d9c4ea18c0cae8 100644
--- a/static/app/utils/profiling/units/units.ts
+++ b/static/app/utils/profiling/units/units.ts
@@ -80,10 +80,10 @@ export function makeTimelineFormatter(from: ProfilingFormatterUnit | string) {
}
return (value: number) => {
- const s = value * multiplier;
+ const s = Math.abs(value * multiplier);
const m = s / 60;
const ms = s * 1e3;
- return `${pad(m, 2)}:${pad(s % 60, 2)}.${pad(ms % 1e3, 3)}`;
+ return `${value < 0 ? '-' : ''}${pad(m, 2)}:${pad(s % 60, 2)}.${pad(ms % 1e3, 3)}`;
};
}
|
e01c0c2b8e302ac14fa022f48f9d132bf5173e23
|
2025-02-10 19:50:09
|
Tony Xiao
|
fix(explore): Do not clear include conditions on exclude (#84803)
| false
|
Do not clear include conditions on exclude (#84803)
|
fix
|
diff --git a/static/app/views/discover/table/cellAction.spec.tsx b/static/app/views/discover/table/cellAction.spec.tsx
index 03b1284b9ce69d..3f1975e523a829 100644
--- a/static/app/views/discover/table/cellAction.spec.tsx
+++ b/static/app/views/discover/table/cellAction.spec.tsx
@@ -466,17 +466,17 @@ describe('updateQuery()', function () {
updateQuery(results, Actions.ADD, columnB, '2');
expect(results.formatString()).toBe('a:1 b:2');
updateQuery(results, Actions.EXCLUDE, columnA, '3');
- expect(results.formatString()).toBe('b:2 !a:3');
+ expect(results.formatString()).toBe('a:1 b:2 !a:3');
updateQuery(results, Actions.EXCLUDE, columnB, '4');
- expect(results.formatString()).toBe('!a:3 !b:4');
+ expect(results.formatString()).toBe('a:1 b:2 !a:3 !b:4');
results.addFilterValues('!a', ['*dontescapeme*'], false);
- expect(results.formatString()).toBe('!a:3 !b:4 !a:*dontescapeme*');
+ expect(results.formatString()).toBe('a:1 b:2 !a:3 !b:4 !a:*dontescapeme*');
updateQuery(results, Actions.EXCLUDE, columnA, '*escapeme*');
expect(results.formatString()).toBe(
- '!b:4 !a:3 !a:*dontescapeme* !a:"\\*escapeme\\*"'
+ 'a:1 b:2 !b:4 !a:3 !a:*dontescapeme* !a:"\\*escapeme\\*"'
);
updateQuery(results, Actions.ADD, columnA, '5');
- expect(results.formatString()).toBe('!b:4 a:5');
+ expect(results.formatString()).toBe('b:2 !b:4 a:5');
updateQuery(results, Actions.ADD, columnB, '6');
expect(results.formatString()).toBe('a:5 b:6');
});
diff --git a/static/app/views/discover/table/cellAction.tsx b/static/app/views/discover/table/cellAction.tsx
index 55d4ccf2211605..d39f26f95824ae 100644
--- a/static/app/views/discover/table/cellAction.tsx
+++ b/static/app/views/discover/table/cellAction.tsx
@@ -115,9 +115,6 @@ export function excludeFromFilter(
key: string,
value: React.ReactText | string[]
) {
- // Remove positive if it exists.
- oldFilter.removeFilter(key);
-
// Negations should stack up.
const negation = `!${key}`;
diff --git a/static/app/views/discover/table/tableView.spec.tsx b/static/app/views/discover/table/tableView.spec.tsx
index 0e91ac74d15f60..b2add2a163a623 100644
--- a/static/app/views/discover/table/tableView.spec.tsx
+++ b/static/app/views/discover/table/tableView.spec.tsx
@@ -242,7 +242,7 @@ describe('TableView > CellActions', function () {
expect(initialData.router.push).toHaveBeenCalledWith({
pathname: location.pathname,
query: expect.objectContaining({
- query: 'tag:value !title:"some title"',
+ query: 'tag:value title:nope !title:"some title"',
}),
});
});
|
53ea1a289dd39111633126d51b4b6289749e0134
|
2022-04-04 13:37:33
|
Evan Purkhiser
|
chore(deps): Upgrade to latest eslint-config-sentry-app (#33243)
| false
|
Upgrade to latest eslint-config-sentry-app (#33243)
|
chore
|
diff --git a/package.json b/package.json
index 87914a728a7a3b..dc7ac0dafebf83 100644
--- a/package.json
+++ b/package.json
@@ -164,7 +164,7 @@
"babel-jest": "27.5.1",
"babel-plugin-dynamic-import-node": "^2.2.0",
"eslint": "7.32.0",
- "eslint-config-sentry-app": "^1.82.0",
+ "eslint-config-sentry-app": "^1.90.0",
"html-webpack-plugin": "^5.5.0",
"jest": "27.5.1",
"jest-canvas-mock": "^2.3.1",
diff --git a/static/app/components/dropdownMenu.tsx b/static/app/components/dropdownMenu.tsx
index ffa4215c824867..8b706045ae1e80 100644
--- a/static/app/components/dropdownMenu.tsx
+++ b/static/app/components/dropdownMenu.tsx
@@ -119,12 +119,6 @@ class DropdownMenu extends React.Component<Props, State> {
isOpen: false,
};
- dropdownMenu: Element | null = null;
- dropdownActor: Element | null = null;
-
- mouseLeaveTimeout: number | null = null;
- mouseEnterTimeout: number | null = null;
-
componentWillUnmount() {
if (this.mouseLeaveTimeout) {
window.clearTimeout(this.mouseLeaveTimeout);
@@ -135,6 +129,12 @@ class DropdownMenu extends React.Component<Props, State> {
document.removeEventListener('click', this.checkClickOutside, true);
}
+ dropdownMenu: Element | null = null;
+ dropdownActor: Element | null = null;
+
+ mouseLeaveTimeout: number | null = null;
+ mouseEnterTimeout: number | null = null;
+
// Gets open state from props or local state when appropriate
isOpen = () => {
const {isOpen} = this.props;
diff --git a/static/app/components/themeAndStyleProvider.tsx b/static/app/components/themeAndStyleProvider.tsx
index 4d295976270475..eb096ab135309a 100644
--- a/static/app/components/themeAndStyleProvider.tsx
+++ b/static/app/components/themeAndStyleProvider.tsx
@@ -1,6 +1,6 @@
import {Fragment, useEffect} from 'react';
import {createPortal} from 'react-dom';
-import {cache} from '@emotion/css'; // eslint-disable-line emotion/no-vanilla
+import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla
import {CacheProvider, ThemeProvider} from '@emotion/react'; // This is needed to set "speedy" = false (for percy)
import {loadPreferencesState} from 'sentry/actionCreators/preferences';
diff --git a/static/app/views/alerts/issueRuleEditor/ruleNodeList.tsx b/static/app/views/alerts/issueRuleEditor/ruleNodeList.tsx
index 683e70c5f9f5c7..a60ccc210fff44 100644
--- a/static/app/views/alerts/issueRuleEditor/ruleNodeList.tsx
+++ b/static/app/views/alerts/issueRuleEditor/ruleNodeList.tsx
@@ -47,14 +47,14 @@ type Props = {
};
class RuleNodeList extends React.Component<Props> {
- propertyChangeTimeout: number | null = null;
-
componentWillUnmount() {
if (this.propertyChangeTimeout) {
window.clearTimeout(this.propertyChangeTimeout);
}
}
+ propertyChangeTimeout: number | null = null;
+
getNode = (
id: string,
itemIdx: number
diff --git a/static/app/views/dashboardsV2/dashboard.tsx b/static/app/views/dashboardsV2/dashboard.tsx
index aec003f3152964..43ff670c3a41d3 100644
--- a/static/app/views/dashboardsV2/dashboard.tsx
+++ b/static/app/views/dashboardsV2/dashboard.tsx
@@ -110,8 +110,6 @@ class Dashboard extends Component<Props, State> {
};
}
- forceCheckTimeout: number | null = null;
-
static getDerivedStateFromProps(props, state) {
if (props.organization.features.includes('dashboard-grid-layout')) {
if (state.isMobile) {
@@ -192,6 +190,8 @@ class Dashboard extends Component<Props, State> {
}
}
+ forceCheckTimeout: number | null = null;
+
debouncedHandleResize = debounce(() => {
this.setState({
windowWidth: window.innerWidth,
diff --git a/tests/js/sentry-test/enzyme.js b/tests/js/sentry-test/enzyme.js
index b4350c99afea2b..74bb5fcea77c58 100644
--- a/tests/js/sentry-test/enzyme.js
+++ b/tests/js/sentry-test/enzyme.js
@@ -1,4 +1,4 @@
-import {cache} from '@emotion/css'; // eslint-disable-line emotion/no-vanilla
+import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla
import {CacheProvider, ThemeProvider} from '@emotion/react';
import {mount, shallow as enzymeShallow} from 'enzyme'; // eslint-disable-line no-restricted-imports
diff --git a/tests/js/sentry-test/reactTestingLibrary.tsx b/tests/js/sentry-test/reactTestingLibrary.tsx
index cac059aa8e86d5..78c3dc95de413a 100644
--- a/tests/js/sentry-test/reactTestingLibrary.tsx
+++ b/tests/js/sentry-test/reactTestingLibrary.tsx
@@ -1,5 +1,5 @@
import {Component, Fragment} from 'react';
-import {cache} from '@emotion/css';
+import {cache} from '@emotion/css'; // eslint-disable-line @emotion/no-vanilla
import {CacheProvider, ThemeProvider} from '@emotion/react';
import * as rtl from '@testing-library/react'; // eslint-disable-line no-restricted-imports
import * as reactHooks from '@testing-library/react-hooks'; // eslint-disable-line no-restricted-imports
diff --git a/tests/js/setup.ts b/tests/js/setup.ts
index b8773d9f94037e..b842e2834c70ee 100644
--- a/tests/js/setup.ts
+++ b/tests/js/setup.ts
@@ -11,6 +11,7 @@ import MockDate from 'mockdate';
import * as PropTypes from 'prop-types';
import * as qs from 'query-string';
+// eslint-disable-next-line jest/no-mocks-import
import type {Client} from 'sentry/__mocks__/api';
import ConfigStore from 'sentry/stores/configStore';
diff --git a/tests/js/spec/utils/tokenizeSearch.spec.jsx b/tests/js/spec/utils/tokenizeSearch.spec.jsx
index 8017addf4f9822..b9dfc02f8229be 100644
--- a/tests/js/spec/utils/tokenizeSearch.spec.jsx
+++ b/tests/js/spec/utils/tokenizeSearch.spec.jsx
@@ -183,6 +183,7 @@ describe('utils/tokenizeSearch', function () {
];
for (const {name, string, object} of cases) {
+ // eslint-disable-next-line jest/valid-title
it(name, () => expect(new MutableSearch(string)).toEqual(object));
}
});
@@ -479,6 +480,7 @@ describe('utils/tokenizeSearch', function () {
];
for (const {name, string, object} of cases) {
+ // eslint-disable-next-line jest/valid-title
it(name, () => expect(object.formatString()).toEqual(string));
}
});
diff --git a/yarn.lock b/yarn.lock
index 482d421b1000ca..29997ebdb4feb0 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1410,6 +1410,11 @@
"@emotion/sheet" "^1.0.0"
"@emotion/utils" "^1.0.0"
+"@emotion/eslint-plugin@^11.7.0":
+ version "11.7.0"
+ resolved "https://registry.yarnpkg.com/@emotion/eslint-plugin/-/eslint-plugin-11.7.0.tgz#253c8ace26f3921695a7aa85ecbf6fac75e74b33"
+ integrity sha512-k6H0OxBgkPDVG5M16AWnu3z15OmmKNvGmJiYTcamoOIDhiGE5+no+BiVAiHPOwJf/NOsDei2S9i015cMwlO5sA==
+
"@emotion/[email protected]", "@emotion/hash@^0.8.0":
version "0.8.0"
resolved "https://registry.yarnpkg.com/@emotion/hash/-/hash-0.8.0.tgz#bbbff68978fefdbe68ccb533bc8cbe1d1afb5413"
@@ -4224,7 +4229,7 @@
resolved "https://registry.yarnpkg.com/@types/js-cookie/-/js-cookie-2.2.7.tgz#226a9e31680835a6188e887f3988e60c04d3f6a3"
integrity sha512-aLkWa0C0vO5b4Sr798E26QgOkss68Un0bLjs7u9qxzPT5CG+8DuNTffWES58YzJs3hrVAOs1wonycqEBqNJubA==
-"@types/json-schema@*", "@types/json-schema@^7.0.3", "@types/json-schema@^7.0.4", "@types/json-schema@^7.0.5", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9":
+"@types/json-schema@*", "@types/json-schema@^7.0.4", "@types/json-schema@^7.0.5", "@types/json-schema@^7.0.8", "@types/json-schema@^7.0.9":
version "7.0.11"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.11.tgz#d421b6c527a3037f7c84433fd2c4229e016863d3"
integrity sha512-wOuvG1SN4Us4rez+tylwwwCV1psiNVOkJeM3AUWUNWg/jDQY2+HE/444y5gc+jBmRqASOm2Oeh5c1axHobwRKQ==
@@ -4597,7 +4602,7 @@
dependencies:
"@types/node" "*"
-"@typescript-eslint/eslint-plugin@^5.14.0":
+"@typescript-eslint/eslint-plugin@^5.17.0":
version "5.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-5.17.0.tgz#704eb4e75039000531255672bf1c85ee85cf1d67"
integrity sha512-qVstvQilEd89HJk3qcbKt/zZrfBZ+9h2ynpAGlWjWiizA7m/MtLT9RoX6gjtpE500vfIg8jogAkDzdCxbsFASQ==
@@ -4612,15 +4617,6 @@
semver "^7.3.5"
tsutils "^3.21.0"
-"@typescript-eslint/experimental-utils@^1.13.0":
- version "1.13.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-1.13.0.tgz#b08c60d780c0067de2fb44b04b432f540138301e"
- integrity sha512-zmpS6SyqG4ZF64ffaJ6uah6tWWWgZ8m+c54XXgwFtUv0jNz8aJAVx8chMCvnk7yl6xwn8d+d96+tWp7fXzTuDg==
- dependencies:
- "@types/json-schema" "^7.0.3"
- "@typescript-eslint/typescript-estree" "1.13.0"
- eslint-scope "^4.0.0"
-
"@typescript-eslint/experimental-utils@^5.0.0":
version "5.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/experimental-utils/-/experimental-utils-5.17.0.tgz#303ba1d766d715c3225a31845b54941889e52f6c"
@@ -4628,7 +4624,7 @@
dependencies:
"@typescript-eslint/utils" "5.17.0"
-"@typescript-eslint/parser@^5.14.0":
+"@typescript-eslint/parser@^5.17.0":
version "5.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-5.17.0.tgz#7def77d5bcd8458d12d52909118cf3f0a45f89d5"
integrity sha512-aRzW9Jg5Rlj2t2/crzhA2f23SIYFlF9mchGudyP0uiD6SenIxzKoLjwzHbafgHn39dNV/TV7xwQkLfFTZlJ4ig==
@@ -4660,14 +4656,6 @@
resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-5.17.0.tgz#861ec9e669ffa2aa9b873dd4d28d9b1ce26d216f"
integrity sha512-AgQ4rWzmCxOZLioFEjlzOI3Ch8giDWx8aUDxyNw9iOeCvD3GEYAB7dxWGQy4T/rPVe8iPmu73jPHuaSqcjKvxw==
-"@typescript-eslint/[email protected]":
- version "1.13.0"
- resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-1.13.0.tgz#8140f17d0f60c03619798f1d628b8434913dc32e"
- integrity sha512-b5rCmd2e6DCC6tCTN9GSUAuxdYwCM/k/2wdjHGrIRGPSJotWMCe/dGpi66u42bhuh8q3QBzqM4TMA1GUUCJvdw==
- dependencies:
- lodash.unescape "4.0.1"
- semver "5.5.0"
-
"@typescript-eslint/[email protected]":
version "5.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-5.17.0.tgz#a7cba7dfc8f9cc2ac78c18584e684507df4f2488"
@@ -4681,7 +4669,7 @@
semver "^7.3.5"
tsutils "^3.21.0"
-"@typescript-eslint/[email protected]", "@typescript-eslint/utils@^5.13.0":
+"@typescript-eslint/[email protected]", "@typescript-eslint/utils@^5.10.0", "@typescript-eslint/utils@^5.13.0":
version "5.17.0"
resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-5.17.0.tgz#549a9e1d491c6ccd3624bc3c1b098f5cfb45f306"
integrity sha512-DVvndq1QoxQH+hFv+MUQHrrWZ7gQ5KcJzyjhzcqB1Y2Xes1UQQkTRPUfRpqhS8mhTWsSb2+iyvDW1Lef5DD7vA==
@@ -7618,47 +7606,45 @@ escodegen@^2.0.0:
optionalDependencies:
source-map "~0.6.1"
[email protected]:
- version "6.3.0"
- resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-6.3.0.tgz#e73b48e59dc49d950843f3eb96d519e2248286a3"
- integrity sha512-EWaGjlDAZRzVFveh2Jsglcere2KK5CJBhkNSa1xs3KfMUGdRiT7lG089eqPdvlzWHpAqaekubOsOMu8W8Yk71A==
- dependencies:
- get-stdin "^6.0.0"
-
-eslint-config-sentry-app@^1.82.0:
- version "1.82.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry-app/-/eslint-config-sentry-app-1.82.0.tgz#e734e8a178bab7fb3cb2d07302f7cda25fed1a74"
- integrity sha512-DqYAElVT3DqadI+k6k6SyhbaaYPAFdVQaq56g0vJ9NsgbGooA+NnsWivEb3Fx78oBQzdjPKwNztLXc+zNrcvow==
- dependencies:
- "@typescript-eslint/eslint-plugin" "^5.14.0"
- "@typescript-eslint/parser" "^5.14.0"
- eslint-config-prettier "6.3.0"
- eslint-config-sentry "^1.82.0"
- eslint-config-sentry-react "^1.82.0"
- eslint-import-resolver-typescript "^2.5.0"
[email protected]:
+ version "8.5.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-8.5.0.tgz#5a81680ec934beca02c7b1a61cf8ca34b66feab1"
+ integrity sha512-obmWKLUNCnhtQRKc+tmnYuQl0pFU1ibYJQ5BGhTVB08bHe9wC8qUeG7c08dj9XX+AuPj1YSGSQIHl1pnDHZR0Q==
+
+eslint-config-sentry-app@^1.90.0:
+ version "1.90.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry-app/-/eslint-config-sentry-app-1.90.0.tgz#94988528da2244f25ab22e5384e7f5402aac8d04"
+ integrity sha512-LW8vtmj7T15D6/bwThzUYToLLft8SnN2aiYxlrz/kMTCL90/x2aX+LMqupKgQ/Ljfjndi2m7J1aiiVI19Cnj/Q==
+ dependencies:
+ "@emotion/eslint-plugin" "^11.7.0"
+ "@typescript-eslint/eslint-plugin" "^5.17.0"
+ "@typescript-eslint/parser" "^5.17.0"
+ eslint-config-prettier "8.5.0"
+ eslint-config-sentry "^1.90.0"
+ eslint-config-sentry-react "^1.90.0"
+ eslint-import-resolver-typescript "^2.7.1"
eslint-import-resolver-webpack "^0.13.2"
- eslint-plugin-emotion "^10.0.27"
- eslint-plugin-import "^2.23.4"
- eslint-plugin-jest "22.17.0"
- eslint-plugin-prettier "3.1.1"
+ eslint-plugin-import "^2.25.4"
+ eslint-plugin-jest "26.1.3"
+ eslint-plugin-prettier "4.0.0"
eslint-plugin-react "7.15.1"
- eslint-plugin-sentry "^1.82.0"
+ eslint-plugin-sentry "^1.90.0"
eslint-plugin-simple-import-sort "^7.0.0"
-eslint-config-sentry-react@^1.82.0:
- version "1.82.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry-react/-/eslint-config-sentry-react-1.82.0.tgz#afcdd53f0e902b26d41a1c5827dd120d6e614e7f"
- integrity sha512-aHY+kO7BT93hOb6ekrFIkgJhfZmNMb7fq6kwAT56ma1lg+8AZufC8bxDoEsoN3WSBP5uUolt2FumrUw/ZO5X3w==
+eslint-config-sentry-react@^1.90.0:
+ version "1.90.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry-react/-/eslint-config-sentry-react-1.90.0.tgz#527d905ea3f89442c12f42b5c8d20ba9e0670ddc"
+ integrity sha512-d8QCFh8WIGfVg3VkHxu9usrONW/EtzZLl1mdw6/p2BytbIQEUlaSKB1rMyp7LnfL8JlbYdiSO8CX0BwQ3iSd5w==
dependencies:
- eslint-config-sentry "^1.82.0"
+ eslint-config-sentry "^1.90.0"
eslint-plugin-jest-dom "^4.0.1"
eslint-plugin-testing-library "^5.0.3"
eslint-plugin-typescript-sort-keys "^2.1.0"
-eslint-config-sentry@^1.82.0:
- version "1.82.0"
- resolved "https://registry.yarnpkg.com/eslint-config-sentry/-/eslint-config-sentry-1.82.0.tgz#b0f339f6076374050c94a9ee1946444f1c25ab8d"
- integrity sha512-X/pbITvVSoRXXfCWIiDZ44+axc5x4EU+1ADBzhzw9jpMdHnkl6GtPYHsZyZC1APHfJ495WLjm74a8EjZhOe9sA==
+eslint-config-sentry@^1.90.0:
+ version "1.90.0"
+ resolved "https://registry.yarnpkg.com/eslint-config-sentry/-/eslint-config-sentry-1.90.0.tgz#6a3677e6e28db76180b2c26c3c52c88ec49c7c22"
+ integrity sha512-dgCxuCzKaAe4lQk7QMSH4nn20eP3OkWSdeMXkvnnG/FAv5q1ag0fnoQJGwTHHgzBVRw8xYHLlbj4pqPxzvaK8A==
eslint-import-resolver-node@^0.3.6:
version "0.3.6"
@@ -7668,10 +7654,10 @@ eslint-import-resolver-node@^0.3.6:
debug "^3.2.7"
resolve "^1.20.0"
-eslint-import-resolver-typescript@^2.5.0:
- version "2.7.0"
- resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-2.7.0.tgz#1f9d391b636dccdbaa4a3b1a87eb9a8237e23963"
- integrity sha512-MNHS3u5pebvROX4MjGP9coda589ZGfL1SqdxUV4kSrcclfDRWvNE2D+eljbnWVMvWDVRgT89nhscMHPKYGcObQ==
+eslint-import-resolver-typescript@^2.7.1:
+ version "2.7.1"
+ resolved "https://registry.yarnpkg.com/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-2.7.1.tgz#a90a4a1c80da8d632df25994c4c5fdcdd02b8751"
+ integrity sha512-00UbgGwV8bSgUv34igBDbTOtKhqoRMy9bFjNehT40bXg6585PNIct8HhXZ0SybqB9rWtXj9crcku8ndDn/gIqQ==
dependencies:
debug "^4.3.4"
glob "^7.2.0"
@@ -7704,12 +7690,7 @@ eslint-module-utils@^2.7.2:
debug "^3.2.7"
find-up "^2.1.0"
-eslint-plugin-emotion@^10.0.27:
- version "10.0.27"
- resolved "https://registry.yarnpkg.com/eslint-plugin-emotion/-/eslint-plugin-emotion-10.0.27.tgz#577a4265cc679f7bb826437a92fb9d709928e0a7"
- integrity sha512-0IG9KWmyQTAWZNM4WoGjFbdre1Xq6uMp2jYOSHvh3ZNcDfOjOLXeH3ky1MuWZlbWIHxz/Ed5DMGlJAeKnd26VA==
-
-eslint-plugin-import@^2.23.4:
+eslint-plugin-import@^2.25.4:
version "2.25.4"
resolved "https://registry.yarnpkg.com/eslint-plugin-import/-/eslint-plugin-import-2.25.4.tgz#322f3f916a4e9e991ac7af32032c25ce313209f1"
integrity sha512-/KJBASVFxpu0xg1kIBn9AUa8hQVnszpwgE7Ld0lKAlx7Ie87yzEzCgSkekt+le/YVhiaosO4Y14GDAOc41nfxA==
@@ -7737,17 +7718,17 @@ eslint-plugin-jest-dom@^4.0.1:
"@testing-library/dom" "^8.11.1"
requireindex "^1.2.0"
[email protected]:
- version "22.17.0"
- resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-22.17.0.tgz#dc170ec8369cd1bff9c5dd8589344e3f73c88cf6"
- integrity sha512-WT4DP4RoGBhIQjv+5D0FM20fAdAUstfYAf/mkufLNTojsfgzc5/IYW22cIg/Q4QBavAZsROQlqppiWDpFZDS8Q==
[email protected]:
+ version "26.1.3"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-jest/-/eslint-plugin-jest-26.1.3.tgz#e722e5efeea18aa9dec7c7349987b641db19feb7"
+ integrity sha512-Pju+T7MFpo5VFhFlwrkK/9jRUu18r2iugvgyrWOnnGRaVTFFmFXp+xFJpHyqmjjLmGJPKLeEFLVTAxezkApcpQ==
dependencies:
- "@typescript-eslint/experimental-utils" "^1.13.0"
+ "@typescript-eslint/utils" "^5.10.0"
[email protected]:
- version "3.1.1"
- resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-3.1.1.tgz#507b8562410d02a03f0ddc949c616f877852f2ba"
- integrity sha512-A+TZuHZ0KU0cnn56/9mfR7/KjUJ9QNVXUhwvRFSR7PGPe0zQR6PTkmyqg1AtUUEOzTqeRsUwyKFh0oVZKVCrtA==
[email protected]:
+ version "4.0.0"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-prettier/-/eslint-plugin-prettier-4.0.0.tgz#8b99d1e4b8b24a762472b4567992023619cb98e0"
+ integrity sha512-98MqmCJ7vJodoQK359bqQWaxOE0CS8paAz/GgjaZLyex4TTk3g9HugoO89EqWCrFiOqn9EVvcoo7gZzONCWVwQ==
dependencies:
prettier-linter-helpers "^1.0.0"
@@ -7766,10 +7747,10 @@ [email protected]:
prop-types "^15.7.2"
resolve "^1.12.0"
-eslint-plugin-sentry@^1.82.0:
- version "1.82.0"
- resolved "https://registry.yarnpkg.com/eslint-plugin-sentry/-/eslint-plugin-sentry-1.82.0.tgz#d97542deda86c8607fd86f94b89719f702de01d6"
- integrity sha512-xNOTN73K8EiWta139PwFMJlKfJgcckQ7l41v0hWxRMPhWBtZlp9rdJxxuE2l3NelolJidxMk5qZFllOFPOu1uA==
+eslint-plugin-sentry@^1.90.0:
+ version "1.90.0"
+ resolved "https://registry.yarnpkg.com/eslint-plugin-sentry/-/eslint-plugin-sentry-1.90.0.tgz#37e5190781310d7e93abb2d8893b3725df5710de"
+ integrity sha512-OLUPpO8ApsSJpkkFhYETEHEooisaO82b68+GZEBdb/SvCSJlcV2rfIUPfst+UJ7SvcXm14O4Gx9SFhVIZbAwKQ==
dependencies:
requireindex "~1.1.0"
@@ -7802,14 +7783,6 @@ [email protected], eslint-scope@^5.1.1:
esrecurse "^4.3.0"
estraverse "^4.1.1"
-eslint-scope@^4.0.0:
- version "4.0.3"
- resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-4.0.3.tgz#ca03833310f6889a3264781aa82e63eb9cfe7848"
- integrity sha512-p7VutNr1O/QrxysMo3E45FjYDTeXBy0iTltPFNSqKAIfjDSXC+4dj+qfyuD8bfAXrW/y6lW3O76VaYNPKfpKrg==
- dependencies:
- esrecurse "^4.1.0"
- estraverse "^4.1.1"
-
eslint-utils@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/eslint-utils/-/eslint-utils-2.1.0.tgz#d2de5e03424e707dc10c74068ddedae708741b27"
@@ -7906,7 +7879,7 @@ esquery@^1.4.0:
dependencies:
estraverse "^5.1.0"
-esrecurse@^4.1.0, esrecurse@^4.3.0:
+esrecurse@^4.3.0:
version "4.3.0"
resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921"
integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==
@@ -8611,11 +8584,6 @@ get-package-type@^0.1.0:
resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a"
integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==
-get-stdin@^6.0.0:
- version "6.0.0"
- resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-6.0.0.tgz#9e09bf712b360ab9225e812048f71fde9c89657b"
- integrity sha512-jp4tHawyV7+fkkSKyvjuLZswblUtz+SQKzSWnBbii16BuZksJlU1wuBYXY75r+duh/llF1ur6oNwi+2ZzjKZ7g==
-
get-stdin@^8.0.0:
version "8.0.0"
resolved "https://registry.yarnpkg.com/get-stdin/-/get-stdin-8.0.0.tgz#cbad6a73feb75f6eeb22ba9e01f89aa28aa97a53"
@@ -10912,11 +10880,6 @@ lodash.truncate@^4.4.2:
resolved "https://registry.yarnpkg.com/lodash.truncate/-/lodash.truncate-4.4.2.tgz#5a350da0b1113b837ecfffd5812cbe58d6eae193"
integrity sha1-WjUNoLERO4N+z//VgSy+WNbq4ZM=
[email protected]:
- version "4.0.1"
- resolved "https://registry.yarnpkg.com/lodash.unescape/-/lodash.unescape-4.0.1.tgz#bf2249886ce514cda112fae9218cdc065211fc9c"
- integrity sha1-vyJJiGzlFM2hEvrpIYzcBlIR/Jw=
-
[email protected], lodash.uniq@^4.5.0:
version "4.5.0"
resolved "https://registry.yarnpkg.com/lodash.uniq/-/lodash.uniq-4.5.0.tgz#d0225373aeb652adc1bc82e4945339a842754773"
@@ -13903,11 +13866,6 @@ selfsigned@^1.10.8:
resolved "https://registry.yarnpkg.com/semver/-/semver-5.7.1.tgz#a954f931aeba508d307bbf069eff0c01c96116f7"
integrity sha512-sauaDf/PZdVgrLTNYHRtpXa1iRiKcaebiKQ1BJdpQlWH2lCvexQdX55snPFyK7QzpudqbCI0qXFfOasHdyNDGQ==
[email protected]:
- version "5.5.0"
- resolved "https://registry.yarnpkg.com/semver/-/semver-5.5.0.tgz#dc4bbc7a6ca9d916dee5d43516f0092b58f7b8ab"
- integrity sha512-4SJ3dm0WAwWy/NVeioZh5AntkdJoWKxHxcmyP622fOkgHa4z3R0TdBJICINyaSDE6uNwVc8gZr+ZinwZAH4xIA==
-
[email protected]:
version "7.0.0"
resolved "https://registry.yarnpkg.com/semver/-/semver-7.0.0.tgz#5f3ca35761e47e05b206c6daff2cf814f0316b8e"
|
c60d3d47adc06cbbd1b6978d0e4bc2cf83ae6de3
|
2024-10-31 22:51:30
|
Colleen O'Rourke
|
fix(alerts): Add back onChange (#80075)
| false
|
Add back onChange (#80075)
|
fix
|
diff --git a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx
index 7e6de0332630b0..a8207076fe5db9 100644
--- a/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx
+++ b/static/app/views/alerts/rules/metric/ruleConditionsForm.tsx
@@ -741,6 +741,7 @@ class RuleConditionsForm extends PureComponent<Props, State> {
searchSource="alert_builder"
filterKeys={filterKeys}
disabled={disabled || isErrorMigration}
+ onChange={onChange}
invalidMessages={{
[InvalidReason.WILDCARD_NOT_ALLOWED]: t(
'The wildcard operator is not supported here.'
|
ba18eb1cfd4c26574f926841fb81e5c16f48e833
|
2022-08-10 21:40:16
|
William Mak
|
feat(mep): Improve metric compat performance (#37581)
| false
|
Improve metric compat performance (#37581)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_events_meta.py b/src/sentry/api/endpoints/organization_events_meta.py
index 4194056774fc3f..cb02896f1920e3 100644
--- a/src/sentry/api/endpoints/organization_events_meta.py
+++ b/src/sentry/api/endpoints/organization_events_meta.py
@@ -95,31 +95,24 @@ def get(self, request: Request, organization) -> Response:
)
sum_metrics = metrics_performance.query(
- selected_columns=["count()"],
+ selected_columns=[count_unparam, count_null, "count()"],
params=params,
- referrer="api.organization-events-metrics-compatibility.sum_metrics",
query="",
+ referrer="api.organization-events-metrics-compatibility.sum_metrics",
+ functions_acl=["count_unparameterized_transactions", "count_null_transactions"],
+ use_aggregate_conditions=True,
)
data["sum"]["metrics"] = (
sum_metrics["data"][0].get("count") if len(sum_metrics["data"]) > 0 else 0
)
-
- sum_unparameterized = metrics_performance.query(
- selected_columns=[count_unparam, count_null],
- params=params,
- referrer="api.organization-events-metrics-compatibility.sum_unparameterized",
- query='transaction:"<< unparameterized >>" OR !has:transaction',
- functions_acl=["count_unparameterized_transactions", "count_null_transactions"],
- use_aggregate_conditions=True,
- )
data["sum"]["metrics_null"] = (
- sum_unparameterized["data"][0].get(get_function_alias(count_null))
- if len(sum_unparameterized["data"]) > 0
+ sum_metrics["data"][0].get(get_function_alias(count_null))
+ if len(sum_metrics["data"]) > 0
else 0
)
data["sum"]["metrics_unparam"] = (
- sum_unparameterized["data"][0].get(get_function_alias(count_unparam))
- if len(sum_unparameterized["data"]) > 0
+ sum_metrics["data"][0].get(get_function_alias(count_unparam))
+ if len(sum_metrics["data"]) > 0
else 0
)
|
1f8e75eebd5788321a89dcbac1d37e2242dfaf11
|
2022-05-05 02:01:42
|
William Mak
|
feat(mep): Add metrics to the vitals endpoint (#34041)
| false
|
Add metrics to the vitals endpoint (#34041)
|
feat
|
diff --git a/src/sentry/api/endpoints/organization_events_vitals.py b/src/sentry/api/endpoints/organization_events_vitals.py
index 51d4160a17067a..82edededf6c59e 100644
--- a/src/sentry/api/endpoints/organization_events_vitals.py
+++ b/src/sentry/api/endpoints/organization_events_vitals.py
@@ -3,6 +3,7 @@
from rest_framework.request import Request
from rest_framework.response import Response
+from sentry import features
from sentry.api.bases import NoProjects, OrganizationEventsV2EndpointBase
from sentry.search.events.fields import get_function_alias
from sentry.snuba import discover
@@ -33,21 +34,32 @@ def get(self, request: Request, organization) -> Response:
if len(vitals) == 0:
raise ParseError(detail="Need to pass at least one vital")
+ performance_use_metrics = features.has(
+ "organizations:performance-use-metrics",
+ organization=organization,
+ actor=request.user,
+ )
+ dataset = self.get_dataset(request) if performance_use_metrics else discover
+ metrics_enhanced = dataset != discover
+ sentry_sdk.set_tag("performance.metrics_enhanced", metrics_enhanced)
+ allow_metric_aggregates = request.GET.get("preventMetricAggregates") != "1"
+
selected_columns = []
- aliases = {}
for vital in vitals:
if vital not in self.VITALS:
raise ParseError(detail=f"{vital} is not a valid vital")
- aliases[vital] = []
- for index, threshold in enumerate(self.VITALS[vital]["thresholds"]):
- column = f"count_at_least({vital}, {threshold})"
- # Order aliases for later calculation
- aliases[vital].append(get_function_alias(column))
- selected_columns.append(column)
- selected_columns.append(f"p75({vital})")
+ selected_columns.extend(
+ [
+ f"p75({vital})",
+ f"count_web_vitals({vital}, good)",
+ f"count_web_vitals({vital}, meh)",
+ f"count_web_vitals({vital}, poor)",
+ f"count_web_vitals({vital}, any)",
+ ]
+ )
with self.handle_query_errors():
- events_results = discover.query(
+ events_results = dataset.query(
selected_columns=selected_columns,
query=request.GET.get("query"),
params=params,
@@ -57,24 +69,24 @@ def get(self, request: Request, organization) -> Response:
auto_fields=True,
auto_aggregations=False,
use_aggregate_conditions=False,
+ allow_metric_aggregates=allow_metric_aggregates,
)
results = {}
if len(events_results["data"]) == 1:
event_data = events_results["data"][0]
for vital in vitals:
- groups = len(aliases[vital])
- results[vital] = {}
- total = 0
-
- # Go backwards so that we can subtract and get the running total
- for i in range(groups - 1, -1, -1):
- count = event_data[aliases[vital][i]]
- group_count = 0 if count is None else count - total
- results[vital][self.LABELS[i]] = group_count
- total += group_count
-
- results[vital]["total"] = total
- results[vital]["p75"] = event_data.get(get_function_alias(f"p75({vital})"))
+ results[vital] = {
+ "p75": event_data.get(get_function_alias(f"p75({vital})")),
+ "total": event_data.get(get_function_alias(f"count_web_vitals({vital}, any)"))
+ or 0,
+ "good": event_data.get(get_function_alias(f"count_web_vitals({vital}, good)"))
+ or 0,
+ "meh": event_data.get(get_function_alias(f"count_web_vitals({vital}, meh)"))
+ or 0,
+ "poor": event_data.get(get_function_alias(f"count_web_vitals({vital}, poor)"))
+ or 0,
+ }
+ results["meta"] = {"isMetricsData": events_results["meta"].get("isMetricsData", False)}
return Response(results)
diff --git a/src/sentry/search/events/datasets/discover.py b/src/sentry/search/events/datasets/discover.py
index 7c4e0879998e46..da62cd31f08004 100644
--- a/src/sentry/search/events/datasets/discover.py
+++ b/src/sentry/search/events/datasets/discover.py
@@ -226,7 +226,7 @@ def function_converter(self) -> Mapping[str, SnQLFunction]:
"count_web_vitals",
required_args=[
NumericColumn("column"),
- SnQLStringArg("quality", allowed_strings=["good", "meh", "poor"]),
+ SnQLStringArg("quality", allowed_strings=["good", "meh", "poor", "any"]),
],
snql_aggregate=self._resolve_web_vital_function,
default_result_type="integer",
@@ -1117,7 +1117,7 @@ def _resolve_web_vital_function(
if quality == "good":
return Function(
"countIf",
- [Function("lessOrEquals", [column, VITAL_THRESHOLDS[column.key]["meh"]])],
+ [Function("less", [column, VITAL_THRESHOLDS[column.key]["meh"]])],
alias,
)
elif quality == "meh":
@@ -1127,21 +1127,21 @@ def _resolve_web_vital_function(
Function(
"and",
[
- Function("greater", [column, VITAL_THRESHOLDS[column.key]["meh"]]),
Function(
- "lessOrEquals", [column, VITAL_THRESHOLDS[column.key]["poor"]]
+ "greaterOrEquals", [column, VITAL_THRESHOLDS[column.key]["meh"]]
),
+ Function("less", [column, VITAL_THRESHOLDS[column.key]["poor"]]),
],
)
],
alias,
)
- else:
+ elif quality == "poor":
return Function(
"countIf",
[
Function(
- "greater",
+ "greaterOrEquals",
[
column,
VITAL_THRESHOLDS[column.key]["poor"],
@@ -1150,6 +1150,20 @@ def _resolve_web_vital_function(
],
alias,
)
+ elif quality == "any":
+ return Function(
+ "countIf",
+ [
+ Function(
+ "greaterOrEquals",
+ [
+ column,
+ 0,
+ ],
+ )
+ ],
+ alias,
+ )
def _resolve_count_miserable_function(self, args: Mapping[str, str], alias: str) -> SelectType:
if args["satisfaction"]:
diff --git a/src/sentry/search/events/datasets/metrics.py b/src/sentry/search/events/datasets/metrics.py
index 8b56b5a880d2ae..6bef3c8870fc3d 100644
--- a/src/sentry/search/events/datasets/metrics.py
+++ b/src/sentry/search/events/datasets/metrics.py
@@ -268,7 +268,9 @@ def function_converter(self) -> Mapping[str, fields.MetricsFunction]:
"measurements.cls",
],
),
- fields.SnQLStringArg("quality", allowed_strings=["good", "meh", "poor"]),
+ fields.SnQLStringArg(
+ "quality", allowed_strings=["good", "meh", "poor", "any"]
+ ),
],
calculated_args=[resolve_metric_id],
snql_distribution=self._resolve_web_vital_function,
@@ -619,6 +621,16 @@ def _resolve_web_vital_function(
measurement_rating = self.builder.resolve_column("measurement_rating")
+ if quality == "any":
+ return Function(
+ "countIf",
+ [
+ Column("value"),
+ Function("equals", [Column("metric_id"), metric_id]),
+ ],
+ alias,
+ )
+
quality_id = self.resolve_value(quality)
if quality_id is None:
return Function(
diff --git a/tests/snuba/api/endpoints/test_organization_events_vitals.py b/tests/snuba/api/endpoints/test_organization_events_vitals.py
index 9d7c8f642b8823..d942cc02ab817b 100644
--- a/tests/snuba/api/endpoints/test_organization_events_vitals.py
+++ b/tests/snuba/api/endpoints/test_organization_events_vitals.py
@@ -3,7 +3,7 @@
from django.urls import reverse
from sentry.models.transaction_threshold import ProjectTransactionThreshold, TransactionMetric
-from sentry.testutils import APITestCase, SnubaTestCase
+from sentry.testutils import APITestCase, MetricsEnhancedPerformanceTestCase, SnubaTestCase
from sentry.testutils.helpers.datetime import before_now, iso_format
from sentry.utils.samples import load_data
@@ -86,6 +86,7 @@ def test_simple(self):
self.query.update({"vital": ["measurements.lcp"]})
response = self.do_request()
assert response.status_code == 200, response.content
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 1,
"meh": 1,
@@ -127,6 +128,7 @@ def test_simple_with_refining_user_misery_filter(self):
)
assert response.status_code == 200, response.content
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 0,
"meh": 1,
@@ -141,7 +143,8 @@ def test_simple_with_refining_user_misery_filter(self):
)
assert response.status_code == 200, response.content
- assert len(response.data) == 1
+ assert len(response.data) == 2
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 0,
"meh": 1,
@@ -167,6 +170,7 @@ def test_grouping(self):
self.query.update({"vital": ["measurements.lcp"]})
response = self.do_request()
assert response.status_code == 200
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 2,
"meh": 3,
@@ -196,6 +200,7 @@ def test_multiple_vitals(self):
)
response = self.do_request()
assert response.status_code == 200
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 0,
"meh": 1,
@@ -241,7 +246,8 @@ def test_transactions_without_vitals(self):
self.query.update({"vital": ["measurements.lcp", "measurements.fcp"]})
response = self.do_request()
- assert response.status_code == 200
+ assert response.status_code == 200, response.data
+ assert not response.data["meta"]["isMetricsData"]
assert response.data["measurements.lcp"] == {
"good": 0,
"meh": 0,
@@ -256,3 +262,216 @@ def test_transactions_without_vitals(self):
"total": 0,
"p75": None,
}
+
+ def test_edges_of_vital_thresholds(self):
+ self.store_event(
+ load_data("transaction", timestamp=self.start),
+ {"lcp": 4000, "fp": 1000, "fcp": 0},
+ project_id=self.project.id,
+ )
+
+ self.query.update({"vital": ["measurements.lcp", "measurements.fp", "measurements.fcp"]})
+ response = self.do_request()
+ assert response.status_code == 200, response.data
+ assert not response.data["meta"]["isMetricsData"]
+ assert response.data["measurements.lcp"] == {
+ "good": 0,
+ "meh": 0,
+ "poor": 1,
+ "total": 1,
+ "p75": 4000,
+ }
+ assert response.data["measurements.fp"] == {
+ "good": 0,
+ "meh": 1,
+ "poor": 0,
+ "total": 1,
+ "p75": 1000,
+ }
+ assert response.data["measurements.fcp"] == {
+ "good": 1,
+ "meh": 0,
+ "poor": 0,
+ "total": 1,
+ "p75": 0,
+ }
+
+
+class OrganizationEventsMetricsEnhancedPerformanceEndpointTest(MetricsEnhancedPerformanceTestCase):
+ METRIC_STRINGS = ["measurement_rating"]
+
+ def setUp(self):
+ super().setUp()
+ self.start = before_now(days=1).replace(hour=10, minute=0, second=0, microsecond=0)
+ self.end = self.start + timedelta(hours=6)
+
+ self.query = {
+ "start": iso_format(self.start),
+ "end": iso_format(self.end),
+ }
+ self.features = {"organizations:performance-use-metrics": True}
+
+ def do_request(self, query=None, features=None):
+ if features is None:
+ features = {"organizations:discover-basic": True}
+ features.update(self.features)
+ if query is None:
+ query = self.query
+ query["dataset"] = "metricsEnhanced"
+
+ self.login_as(user=self.user)
+ with self.feature(features):
+ url = reverse(
+ "sentry-api-0-organization-events-vitals",
+ kwargs={"organization_slug": self.organization.slug},
+ )
+
+ with self.feature(features):
+ return self.client.get(url, query, format="json")
+
+ def test_no_projects(self):
+ response = self.do_request()
+ assert response.status_code == 200, response.content
+ assert len(response.data) == 0
+
+ def test_no_vitals(self):
+ self.query.update({"vital": [], "project": self.project.id})
+ response = self.do_request()
+ assert response.status_code == 400, response.content
+ assert "Need to pass at least one vital" == response.data["detail"]
+
+ def test_simple(self):
+ for rating, lcp in [("good", 2000), ("meh", 3000), ("poor", 5000)]:
+ self.store_metric(
+ lcp,
+ metric="measurements.lcp",
+ tags={"transaction": "foo_transaction", "measurement_rating": rating},
+ timestamp=self.start + timedelta(minutes=5),
+ )
+
+ self.query.update({"vital": ["measurements.lcp"]})
+ response = self.do_request()
+ assert response.status_code == 200, response.content
+ assert response.data["meta"]["isMetricsData"]
+ assert response.data["measurements.lcp"] == {
+ "good": 1,
+ "meh": 1,
+ "poor": 1,
+ "total": 3,
+ "p75": 4000,
+ }
+
+ def test_grouping(self):
+ counts = [
+ ("good", 100, 2),
+ ("meh", 3000, 3),
+ ("poor", 4500, 1),
+ ]
+ for rating, duration, count in counts:
+ for _ in range(count):
+ self.store_metric(
+ duration,
+ metric="measurements.lcp",
+ tags={"transaction": "foo_transaction", "measurement_rating": rating},
+ timestamp=self.start + timedelta(minutes=5),
+ )
+
+ self.query.update({"vital": ["measurements.lcp"]})
+ response = self.do_request()
+ assert response.status_code == 200
+ assert response.data["meta"]["isMetricsData"]
+ assert response.data["measurements.lcp"] == {
+ "good": 2,
+ "meh": 3,
+ "poor": 1,
+ "total": 6,
+ "p75": 3000,
+ }
+
+ def test_multiple_vitals(self):
+ vitals = [
+ ("measurements.lcp", 3000, "meh"),
+ ("measurements.fid", 50, "good"),
+ ("measurements.cls", 0.15, "meh"),
+ ("measurements.fcp", 5000, "poor"),
+ ("measurements.fp", 4000, "poor"),
+ ]
+ for vital, duration, rating in vitals:
+ self.store_metric(
+ duration,
+ metric=vital,
+ tags={"transaction": "foo_transaction", "measurement_rating": rating},
+ timestamp=self.start + timedelta(minutes=5),
+ )
+
+ self.query.update(
+ {
+ "vital": [
+ "measurements.lcp",
+ "measurements.fid",
+ "measurements.cls",
+ "measurements.fcp",
+ "measurements.fp",
+ ]
+ }
+ )
+ response = self.do_request()
+ assert response.status_code == 200
+ assert response.data["meta"]["isMetricsData"]
+ assert response.data["measurements.lcp"] == {
+ "good": 0,
+ "meh": 1,
+ "poor": 0,
+ "total": 1,
+ "p75": 3000,
+ }
+ assert response.data["measurements.fid"] == {
+ "good": 1,
+ "meh": 0,
+ "poor": 0,
+ "total": 1,
+ "p75": 50,
+ }
+ assert response.data["measurements.cls"] == {
+ "good": 0,
+ "meh": 1,
+ "poor": 0,
+ "total": 1,
+ "p75": 0.15,
+ }
+ assert response.data["measurements.fcp"] == {
+ "good": 0,
+ "meh": 0,
+ "poor": 1,
+ "total": 1,
+ "p75": 5000,
+ }
+ assert response.data["measurements.fp"] == {
+ "good": 0,
+ "meh": 0,
+ "poor": 1,
+ "total": 1,
+ "p75": 4000,
+ }
+
+ def test_transactions_without_vitals(self):
+ self.query.update(
+ {"vital": ["measurements.lcp", "measurements.fcp"], "project": self.project.id}
+ )
+ response = self.do_request()
+ assert response.status_code == 200, response.data
+ assert response.data["meta"]["isMetricsData"]
+ assert response.data["measurements.lcp"] == {
+ "good": 0,
+ "meh": 0,
+ "poor": 0,
+ "total": 0,
+ "p75": 0,
+ }
+ assert response.data["measurements.fcp"] == {
+ "good": 0,
+ "meh": 0,
+ "poor": 0,
+ "total": 0,
+ "p75": 0,
+ }
|
7855853c120760856ac1530346eb1a2d3c4a8b00
|
2020-07-28 22:57:31
|
Dan Fuller
|
refs(tests): Backport Django `transactions.on_commit` test helper. (#20056)
| false
|
Backport Django `transactions.on_commit` test helper. (#20056)
|
refs
|
diff --git a/src/sentry/testutils/cases.py b/src/sentry/testutils/cases.py
index 72d6785c577060..79d0dc92203f93 100644
--- a/src/sentry/testutils/cases.py
+++ b/src/sentry/testutils/cases.py
@@ -26,6 +26,7 @@
import requests
import six
import inspect
+from contextlib import contextmanager
from sentry.utils.compat import mock
from click.testing import CliRunner
@@ -82,13 +83,7 @@
from .fixtures import Fixtures
from .factories import Factories
from .skips import requires_snuba
-from .helpers import (
- AuthProvider,
- Feature,
- TaskRunner,
- override_options,
- parse_queries,
-)
+from .helpers import AuthProvider, Feature, TaskRunner, override_options, parse_queries
DEFAULT_USER_AGENT = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
@@ -107,6 +102,25 @@ def setup_dummy_auth_provider(self):
def tasks(self):
return TaskRunner()
+ @classmethod
+ @contextmanager
+ def capture_on_commit_callbacks(cls, using=DEFAULT_DB_ALIAS, execute=False):
+ """
+ Context manager to capture transaction.on_commit() callbacks.
+ Backported from Django:
+ https://github.com/django/django/pull/12944
+ """
+ callbacks = []
+ start_count = len(connections[using].run_on_commit)
+ try:
+ yield callbacks
+ finally:
+ run_on_commit = connections[using].run_on_commit[start_count:]
+ callbacks[:] = [func for sids, func in run_on_commit]
+ if execute:
+ for callback in callbacks:
+ callback()
+
def feature(self, names):
"""
>>> with self.feature({'feature:name': True})
@@ -751,7 +765,7 @@ def snuba_insert(self, events):
assert (
requests.post(
- settings.SENTRY_SNUBA + "/tests/events/insert", data=json.dumps(events),
+ settings.SENTRY_SNUBA + "/tests/events/insert", data=json.dumps(events)
).status_code
== 200
)
|
2158e7cbe024c9e5cd1859fa394e642d5174a31d
|
2024-12-05 05:16:04
|
Scott Cooper
|
fix(settings): Disable data scrub settings w/o permissions (#81641)
| false
|
Disable data scrub settings w/o permissions (#81641)
|
fix
|
diff --git a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
index c498340ecce4a1..d9416cfc08eb67 100644
--- a/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
+++ b/static/app/data/forms/projectSecurityAndPrivacyGroups.tsx
@@ -1,6 +1,9 @@
+import {hasEveryAccess} from 'sentry/components/acl/access';
import type {JsonFormObject} from 'sentry/components/forms/types';
import Link from 'sentry/components/links/link';
import {t, tct} from 'sentry/locale';
+import type {Organization} from 'sentry/types/organization';
+import type {Project} from 'sentry/types/project';
import {convertMultilineFieldValue, extractMultilineFields} from 'sentry/utils';
import {
formatStoreCrashReports,
@@ -11,12 +14,46 @@ import {
// Export route to make these forms searchable by label/help
export const route = '/settings/:orgId/projects/:projectId/security-and-privacy/';
-const ORG_DISABLED_REASON = t(
- "This option is enforced by your organization's settings and cannot be customized per-project."
-);
-
// Check if a field has been set AND IS TRUTHY at the organization level.
-const hasOrgOverride = ({organization, name}) => organization[name];
+const hasOrgOverride = ({
+ organization,
+ name,
+}: {
+ name: string;
+ organization: Organization;
+}) => organization[name];
+
+function hasProjectWriteAndOrgOverride({
+ organization,
+ project,
+ name,
+}: {
+ name: string;
+ organization: Organization;
+ project: Project;
+}) {
+ if (hasOrgOverride({organization, name})) {
+ return true;
+ }
+
+ return !hasEveryAccess(['project:write'], {organization, project});
+}
+
+function projectWriteAndOrgOverrideDisabledReason({
+ organization,
+ name,
+}: {
+ name: string;
+ organization: Organization;
+}) {
+ if (hasOrgOverride({organization, name})) {
+ return t(
+ "This option is enforced by your organization's settings and cannot be customized per-project."
+ );
+ }
+
+ return null;
+}
const formGroups: JsonFormObject[] = [
{
@@ -63,8 +100,8 @@ const formGroups: JsonFormObject[] = [
name: 'dataScrubber',
type: 'boolean',
label: t('Data Scrubber'),
- disabled: hasOrgOverride,
- disabledReason: ORG_DISABLED_REASON,
+ disabled: hasProjectWriteAndOrgOverride,
+ disabledReason: projectWriteAndOrgOverrideDisabledReason,
help: t('Enable server-side data scrubbing'),
'aria-label': t('Enable server-side data scrubbing'),
// `props` are the props given to FormField
@@ -76,8 +113,8 @@ const formGroups: JsonFormObject[] = [
{
name: 'dataScrubberDefaults',
type: 'boolean',
- disabled: hasOrgOverride,
- disabledReason: ORG_DISABLED_REASON,
+ disabled: hasProjectWriteAndOrgOverride,
+ disabledReason: projectWriteAndOrgOverrideDisabledReason,
label: t('Use Default Scrubbers'),
help: t(
'Apply default scrubbers to prevent things like passwords and credit cards from being stored'
@@ -94,8 +131,8 @@ const formGroups: JsonFormObject[] = [
{
name: 'scrubIPAddresses',
type: 'boolean',
- disabled: hasOrgOverride,
- disabledReason: ORG_DISABLED_REASON,
+ disabled: hasProjectWriteAndOrgOverride,
+ disabledReason: projectWriteAndOrgOverrideDisabledReason,
// `props` are the props given to FormField
setValue: (val, props) => props.organization?.[props.name] || val,
label: t('Prevent Storing of IP Addresses'),
diff --git a/static/app/views/settings/projectSecurityAndPrivacy/index.spec.tsx b/static/app/views/settings/projectSecurityAndPrivacy/index.spec.tsx
index 0ff6dca45d69a0..b8adf72054965a 100644
--- a/static/app/views/settings/projectSecurityAndPrivacy/index.spec.tsx
+++ b/static/app/views/settings/projectSecurityAndPrivacy/index.spec.tsx
@@ -87,4 +87,22 @@ describe('projectSecurityAndPrivacy', function () {
screen.getByRole('checkbox', {name: 'Enable server-side data scrubbing'})
).toBeChecked();
});
+
+ it('disables fields when missing project:write access', function () {
+ const {organization} = initializeOrg({
+ organization: {
+ access: [], // Remove all access
+ },
+ });
+ const project = ProjectFixture();
+
+ render(<ProjectSecurityAndPrivacy project={project} organization={organization} />);
+
+ // Check that the data scrubber toggle is disabled
+ expect(
+ screen.getByRole('checkbox', {
+ name: 'Enable server-side data scrubbing',
+ })
+ ).toBeDisabled();
+ });
});
diff --git a/static/app/views/settings/projectSecurityAndPrivacy/index.tsx b/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
index 0749a85bb3d186..599cdecd31e443 100644
--- a/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
+++ b/static/app/views/settings/projectSecurityAndPrivacy/index.tsx
@@ -53,7 +53,7 @@ export default function ProjectSecurityAndPrivacy({organization, project}: Props
onSubmitError={() => addErrorMessage('Unable to save change')}
>
<JsonForm
- additionalFieldProps={{organization}}
+ additionalFieldProps={{organization, project}}
features={features}
disabled={!hasAccess}
forms={projectSecurityAndPrivacyGroups}
|
dfb137d87e76eea4f2acabb4470aca2f90aa783a
|
2023-03-14 23:34:18
|
Zach Collins
|
chore(hybrid-cloud): transactions for metrics (#45592)
| false
|
transactions for metrics (#45592)
|
chore
|
diff --git a/src/sentry/models/outbox.py b/src/sentry/models/outbox.py
index 0a9d9edbf0a2a1..4db772c85d6740 100644
--- a/src/sentry/models/outbox.py
+++ b/src/sentry/models/outbox.py
@@ -4,9 +4,11 @@
import contextlib
import datetime
import sys
+import time
from enum import IntEnum
from typing import Any, Generator, Iterable, List, Mapping, Set, Type, TypeVar
+import sentry_sdk
from django.db import connections, models, router, transaction
from django.db.models import Max
from django.dispatch import Signal
@@ -23,6 +25,7 @@
)
from sentry.silo import SiloMode
from sentry.utils import metrics
+from sentry.utils.sdk import set_measurement
THE_PAST = datetime.datetime(2016, 8, 1, 0, 0, 0, 0, tzinfo=timezone.utc)
@@ -174,24 +177,26 @@ def process_coalesced(self) -> Generator[OutboxBase | None, None, None]:
if coalesced is not None:
first_coalesced: OutboxBase = self.select_coalesced_messages().first() or coalesced
_, deleted = self.select_coalesced_messages().filter(id__lte=coalesced.id).delete()
- tags = {"category": OutboxCategory(self.category).name}
- metrics.incr("outbox.processed", deleted, tags=tags)
- metrics.timing(
+
+ set_measurement(
"outbox.processing_lag",
datetime.datetime.now().timestamp() - first_coalesced.scheduled_from.timestamp(),
- tags=tags,
+ "second",
)
def process(self) -> bool:
- with self.process_coalesced() as coalesced:
- if coalesced is not None:
- with metrics.timer(
- "outbox.send_signal.duration",
- tags={"category": OutboxCategory(coalesced.category).name},
- ):
- coalesced.send_signal()
- return True
- return False
+ with sentry_sdk.start_transaction(op="outbox.process", name="outboxprocess") as transaction:
+ transaction.set_tag("category_name", OutboxCategory(self.category).name)
+ transaction.set_data("shard", self.key_from(self.coalesced_columns))
+ with self.process_coalesced() as coalesced:
+ if coalesced is not None:
+ start = time.monotonic()
+ try:
+ coalesced.send_signal()
+ finally:
+ set_measurement("send_signal_duration", time.monotonic() - start, "second")
+ return True
+ return False
@abc.abstractmethod
def send_signal(self):
diff --git a/src/sentry/services/hybrid_cloud/__init__.py b/src/sentry/services/hybrid_cloud/__init__.py
index a09d14e65702b9..35fca92fe9708d 100644
--- a/src/sentry/services/hybrid_cloud/__init__.py
+++ b/src/sentry/services/hybrid_cloud/__init__.py
@@ -2,8 +2,10 @@
import contextlib
import dataclasses
+import functools
import inspect
import logging
+import random
import threading
from abc import ABC, abstractmethod
from typing import (
@@ -15,6 +17,7 @@
Generic,
List,
Mapping,
+ MutableMapping,
Type,
TypeVar,
cast,
@@ -22,6 +25,8 @@
import sentry_sdk
from rest_framework.request import Request
+from sentry_sdk import Hub
+from sentry_sdk.tracing import Transaction
from sentry.utils.cursors import Cursor, CursorResult
from sentry.utils.pagination_factory import (
@@ -184,7 +189,60 @@ def silo_mode_delegation(
Simply creates a DelegatedBySiloMode from a mapping object, but casts it as a ServiceInterface matching
the mapping values.
"""
- return cast(ServiceInterface, DelegatedBySiloMode(mapping))
+ new_mapping: MutableMapping[SiloMode, Callable[[], ServiceInterface]] = {}
+ for k, factory in mapping.items():
+ new_mapping[k] = _annotate_with_metrics(factory)
+ return cast(ServiceInterface, DelegatedBySiloMode(new_mapping))
+
+
+def _factory_decorator(
+ decorate_service: Callable[[ServiceInterface], None]
+) -> Callable[[Callable[[], ServiceInterface]], Callable[[], ServiceInterface]]:
+ """
+ Creates a decorator for service factories that decorates each instance with the given decorate_service callable.
+ Useful for say, adding metrics to service methods.
+ """
+
+ def decorator(factory: Callable[[], ServiceInterface]) -> Callable[[], ServiceInterface]:
+ def wrapper() -> ServiceInterface:
+ result: ServiceInterface = factory()
+ decorate_service(result)
+ return result
+
+ functools.update_wrapper(wrapper, factory)
+ return wrapper
+
+ return decorator
+
+
+@_factory_decorator
+def _annotate_with_metrics(service: ServiceInterface) -> None:
+ service_name = type(service).__name__
+ for Super in type(service).__bases__:
+ for attr in dir(Super):
+ base_val = getattr(Super, attr)
+ if getattr(base_val, "__isabstractmethod__", False):
+ setattr(
+ service, attr, _wrap_with_metrics(getattr(service, attr), service_name, attr)
+ )
+
+
+def _wrap_with_metrics(
+ m: Callable[..., Any], service_class_name: str, method_name: str
+) -> Callable[..., Any]:
+ def wrapper(*args: Any, **kwds: Any) -> Any:
+ with sentry_sdk.start_transaction(
+ name=f"hybrid_cloud.services.{service_class_name}.{method_name}",
+ op="execute",
+ sampled=random.random() < 0.1,
+ ):
+ transaction: Transaction | None = Hub.current.scope.transaction
+ if transaction:
+ transaction.set_tag("silo_mode", SiloMode.get_current_mode().name)
+ return m(*args, **kwds)
+
+ functools.update_wrapper(wrapper, m)
+ return wrapper
@dataclasses.dataclass
diff --git a/src/sentry/tasks/deletion/hybrid_cloud.py b/src/sentry/tasks/deletion/hybrid_cloud.py
index 4e94dd52af1d57..5d6ad94f889807 100644
--- a/src/sentry/tasks/deletion/hybrid_cloud.py
+++ b/src/sentry/tasks/deletion/hybrid_cloud.py
@@ -23,7 +23,8 @@
from sentry.models import TombstoneBase
from sentry.silo import SiloMode
from sentry.tasks.base import instrumented_task
-from sentry.utils import json, metrics, redis
+from sentry.utils import json, redis
+from sentry.utils.sdk import set_measurement
def deletion_silo_modes() -> List[SiloMode]:
@@ -59,14 +60,8 @@ def set_watermark(
get_watermark_key(prefix, field),
json.dumps((value, sha1(prev_transaction_id.encode("utf8")).hexdigest())),
)
- metrics.gauge(
- "deletion.hybrid_cloud.low_bound",
- value,
- tags=dict(
- field_name=f"{field.model._meta.db_table}.{field.name}",
- watermark=prefix,
- ),
- )
+
+ set_measurement("low_bound", value)
def chunk_watermark_batch(
@@ -176,59 +171,62 @@ def _process_tombstone_reconciliation(
watermark_manager: Manager = field.model.objects
watermark_target = "r"
- low, up, has_more, tid = chunk_watermark_batch(
- prefix, field, watermark_manager, batch_size=get_batch_size()
- )
- to_delete_ids: List[int] = []
- if low < up:
- oldest_seen: datetime.datetime = timezone.now()
-
- with connections[router.db_for_read(model)].cursor() as conn:
- conn.execute(
- f"""
- SELECT r.id, t.created_at FROM {model._meta.db_table} r JOIN {tombstone_cls._meta.db_table} t
- ON t.table_name = %(table_name)s AND t.object_identifier = r.{field.name}
- WHERE {watermark_target}.id > %(low)s AND {watermark_target}.id <= %(up)s
- """,
- {
- "table_name": field.foreign_table_name,
- "low": low,
- "up": up,
- },
- )
-
- for (row_id, tomb_created) in conn.fetchall():
- to_delete_ids.append(row_id)
- oldest_seen = min(oldest_seen, tomb_created)
+ with sentry_sdk.start_transaction(
+ name="deletion.hybrid_cloud.process_tombstone_reconciliation", op="process"
+ ) as transaction:
+ transaction.set_tag("field_name", f"{model._meta.db_table}.{field.name}")
+ transaction.set_tag("watermark", prefix)
- if field.on_delete == "CASCADE":
- task = deletions.get(
- model=model,
- query={"id__in": to_delete_ids},
- transaction_id=tid,
- )
-
- if task.chunk():
- has_more = True # The current batch is not complete, rerun this task again
- else:
+ low, up, has_more, tid = chunk_watermark_batch(
+ prefix, field, watermark_manager, batch_size=get_batch_size()
+ )
+ to_delete_ids: List[int] = []
+ if low < up:
+ oldest_seen: datetime.datetime = timezone.now()
+
+ with connections[router.db_for_read(model)].cursor() as conn:
+ conn.execute(
+ f"""
+ SELECT r.id, t.created_at FROM {model._meta.db_table} r JOIN {tombstone_cls._meta.db_table} t
+ ON t.table_name = %(table_name)s AND t.object_identifier = r.{field.name}
+ WHERE {watermark_target}.id > %(low)s AND {watermark_target}.id <= %(up)s
+ """,
+ {
+ "table_name": field.foreign_table_name,
+ "low": low,
+ "up": up,
+ },
+ )
+
+ for (row_id, tomb_created) in conn.fetchall():
+ to_delete_ids.append(row_id)
+ oldest_seen = min(oldest_seen, tomb_created)
+
+ if field.on_delete == "CASCADE":
+ task = deletions.get(
+ model=model,
+ query={"id__in": to_delete_ids},
+ transaction_id=tid,
+ )
+
+ if task.chunk():
+ has_more = True # The current batch is not complete, rerun this task again
+ else:
+ set_watermark(prefix, field, up, tid)
+
+ elif field.on_delete == "SET_NULL":
+ model.objects.filter(id__in=to_delete_ids).update(**{field.name: None})
set_watermark(prefix, field, up, tid)
- elif field.on_delete == "SET_NULL":
- model.objects.filter(id__in=to_delete_ids).update(**{field.name: None})
- set_watermark(prefix, field, up, tid)
-
- else:
- raise ValueError(
- f"{field.model.__name__}.{field.name} has unexpected on_delete={field.on_delete}, could not process delete!"
+ else:
+ raise ValueError(
+ f"{field.model.__name__}.{field.name} has unexpected on_delete={field.on_delete}, could not process delete!"
+ )
+
+ set_measurement(
+ "processing_lag",
+ datetime.datetime.now().timestamp() - oldest_seen.timestamp(),
+ "second",
)
- metrics.timing(
- "deletion.hybrid_cloud.processing_lag",
- datetime.datetime.now().timestamp() - oldest_seen.timestamp(),
- tags=dict(
- field_name=f"{model._meta.db_table}.{field.name}",
- watermark=prefix,
- ),
- )
-
return has_more
|
a81fd0ef8d4fcdd57f43f0ac78d613fb0e398a4b
|
2024-06-25 22:43:10
|
Luca Forstner
|
ref(wizard): Clean up wizard login success page (#73294)
| false
|
Clean up wizard login success page (#73294)
|
ref
|
diff --git a/static/app/views/setupWizard/index.tsx b/static/app/views/setupWizard/index.tsx
index f9aaa1239a295e..9d2691e22f6090 100644
--- a/static/app/views/setupWizard/index.tsx
+++ b/static/app/views/setupWizard/index.tsx
@@ -1,11 +1,11 @@
import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
import styled from '@emotion/styled';
-import {LinkButton} from 'sentry/components/button';
-import ButtonBar from 'sentry/components/buttonBar';
import LoadingIndicator from 'sentry/components/loadingIndicator';
import {ThemeAndStyleProvider} from 'sentry/components/themeAndStyleProvider';
+import {IconCheckmark} from 'sentry/icons/iconCheckmark';
import {t} from 'sentry/locale';
+import {space} from 'sentry/styles/space';
import type {Organization} from 'sentry/types/organization';
import {trackAnalytics} from 'sentry/utils/analytics';
import useApi from 'sentry/utils/useApi';
@@ -15,17 +15,6 @@ type Props = {
organizations?: Organization[];
};
-const platformDocsMapping = {
- 'javascript-nextjs':
- 'https://docs.sentry.io/platforms/javascript/guides/nextjs/#verify',
- 'javascript-sveltekit':
- 'https://docs.sentry.io/platforms/javascript/guides/sveltekit/#verify',
- 'react-native': 'https://docs.sentry.io/platforms/react-native/#verify',
- cordova: 'https://docs.sentry.io/platforms/javascript/guides/cordova/#verify',
- 'javascript-electron':
- 'https://docs.sentry.io/platforms/javascript/guides/electron/#verify',
-};
-
function SetupWizard({hash = false, organizations}: Props) {
const api = useApi();
const closeTimeoutRef = useRef<number | undefined>(undefined);
@@ -48,11 +37,6 @@ function SetupWizard({hash = false, organizations}: Props) {
[organization, projectPlatform]
);
- // outside of route context
- const docsLink = useMemo(() => {
- return platformDocsMapping[projectPlatform || ''] || 'https://docs.sentry.io/';
- }, [projectPlatform]);
-
useEffect(() => {
return () => {
if (closeTimeoutRef.current) {
@@ -92,47 +76,34 @@ function SetupWizard({hash = false, organizations}: Props) {
return (
<ThemeAndStyleProvider>
- <div className="container">
- {!finished ? (
- <LoadingIndicator style={{margin: '2em auto'}}>
- <div className="row">
- <h5>{t('Waiting for wizard to connect')}</h5>
- </div>
- </LoadingIndicator>
- ) : (
- <div className="row">
- <h5>{t('Return to your terminal to complete your setup')}</h5>
- <MinWidthButtonBar gap={1}>
- <LinkButton
- priority="primary"
- href="/"
- onClick={() =>
- trackAnalytics('setup_wizard.clicked_viewed_issues', analyticsParams)
- }
- >
- {t('View Issues')}
- </LinkButton>
- <LinkButton
- href={docsLink}
- external
- onClick={() =>
- trackAnalytics('setup_wizard.clicked_viewed_docs', analyticsParams)
- }
- >
- {t('See Docs')}
- </LinkButton>
- </MinWidthButtonBar>
- </div>
- )}
- </div>
+ {!finished ? (
+ <LoadingIndicator style={{margin: '2em auto'}}>
+ <h5>{t('Waiting for wizard to connect')}</h5>
+ </LoadingIndicator>
+ ) : (
+ <SuccessWrapper>
+ <SuccessCheckmark color="green300" size="xl" isCircled />
+ <SuccessHeading>
+ {t('Return to your terminal to complete your setup.')}
+ </SuccessHeading>
+ </SuccessWrapper>
+ )}
</ThemeAndStyleProvider>
);
}
-const MinWidthButtonBar = styled(ButtonBar)`
- width: min-content;
- margin-top: 20px;
- margin-bottom: 20px;
+const SuccessCheckmark = styled(IconCheckmark)`
+ flex-shrink: 0;
+`;
+
+const SuccessHeading = styled('h5')`
+ margin: 0;
+`;
+
+const SuccessWrapper = styled('div')`
+ display: flex;
+ align-items: center;
+ gap: ${space(3)};
`;
export default SetupWizard;
|
0f9b4f887f8e8cfaa3e5529c97d7fbe914816bef
|
2019-07-23 02:33:52
|
Alberto Leal
|
feat(apm): Update props to address proptype warnings for new transaction attributes (SEN-800) (#14040)
| false
|
Update props to address proptype warnings for new transaction attributes (SEN-800) (#14040)
|
feat
|
diff --git a/src/sentry/static/sentry/app/components/eventOrGroupHeader.jsx b/src/sentry/static/sentry/app/components/eventOrGroupHeader.jsx
index bedd78e4a40964..3629debe5e3795 100644
--- a/src/sentry/static/sentry/app/components/eventOrGroupHeader.jsx
+++ b/src/sentry/static/sentry/app/components/eventOrGroupHeader.jsx
@@ -5,7 +5,7 @@ import styled, {css} from 'react-emotion';
import classNames from 'classnames';
import {capitalize} from 'lodash';
-import {Metadata} from 'app/sentryTypes';
+import SentryTypes from 'app/sentryTypes';
import EventOrGroupTitle from 'app/components/eventOrGroupTitle';
import Tooltip from 'app/components/tooltip';
import {getMessage, getLocation} from 'app/utils/events';
@@ -17,22 +17,7 @@ class EventOrGroupHeader extends React.Component {
static propTypes = {
params: PropTypes.object,
/** Either an issue or event **/
- data: PropTypes.shape({
- id: PropTypes.string,
- level: PropTypes.string,
- type: PropTypes.oneOf([
- 'error',
- 'csp',
- 'hpkp',
- 'expectct',
- 'expectstaple',
- 'default',
- ]).isRequired,
- title: PropTypes.string,
- metadata: Metadata,
- groupID: PropTypes.string,
- culprit: PropTypes.string,
- }),
+ data: PropTypes.oneOfType([SentryTypes.Event, SentryTypes.Group]),
includeLink: PropTypes.bool,
hideIcons: PropTypes.bool,
hideLevel: PropTypes.bool,
diff --git a/src/sentry/static/sentry/app/components/eventOrGroupTitle.jsx b/src/sentry/static/sentry/app/components/eventOrGroupTitle.jsx
index f5f07a118374e0..58b7a0c13a7c53 100644
--- a/src/sentry/static/sentry/app/components/eventOrGroupTitle.jsx
+++ b/src/sentry/static/sentry/app/components/eventOrGroupTitle.jsx
@@ -13,6 +13,7 @@ class EventOrGroupTitle extends React.Component {
'expectct',
'expectstaple',
'default',
+ 'transaction',
]).isRequired,
title: PropTypes.string,
metadata: Metadata.isRequired,
diff --git a/src/sentry/static/sentry/app/components/events/groupingInfo.jsx b/src/sentry/static/sentry/app/components/events/groupingInfo.jsx
index 9d15e6580dc22e..c8d3ff8af00653 100644
--- a/src/sentry/static/sentry/app/components/events/groupingInfo.jsx
+++ b/src/sentry/static/sentry/app/components/events/groupingInfo.jsx
@@ -248,7 +248,6 @@ class EventGroupingInfo extends AsyncComponent {
static propTypes = {
api: PropTypes.object,
organization: SentryTypes.Organization.isRequired,
- group: SentryTypes.Group.isRequired,
projectId: PropTypes.string.isRequired,
event: SentryTypes.Event.isRequired,
};
diff --git a/src/sentry/static/sentry/app/sentryTypes.jsx b/src/sentry/static/sentry/app/sentryTypes.jsx
index 5de110892074e9..0abbf0e450c862 100644
--- a/src/sentry/static/sentry/app/sentryTypes.jsx
+++ b/src/sentry/static/sentry/app/sentryTypes.jsx
@@ -148,6 +148,16 @@ export const Member = PropTypes.shape({
user: User,
});
+const EventOrGroupType = PropTypes.oneOf([
+ 'error',
+ 'csp',
+ 'hpkp',
+ 'expectct',
+ 'expectstaple',
+ 'default',
+ 'transaction',
+]);
+
export const Group = PropTypes.shape({
id: PropTypes.string.isRequired,
annotations: PropTypes.array,
@@ -174,7 +184,7 @@ export const Group = PropTypes.shape({
status: PropTypes.string,
statusDetails: PropTypes.object,
title: PropTypes.string,
- type: PropTypes.oneOf(['error', 'csp', 'default']),
+ type: EventOrGroupType,
userCount: PropTypes.number,
});
@@ -186,7 +196,7 @@ export const Event = PropTypes.shape({
dateReceived: PropTypes.string,
entries: PropTypes.arrayOf(
PropTypes.shape({
- data: PropTypes.object,
+ data: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
type: PropTypes.string,
})
),
@@ -212,7 +222,7 @@ export const Event = PropTypes.shape({
value: PropTypes.string,
})
),
- type: PropTypes.oneOf(['error', 'csp', 'default']),
+ type: EventOrGroupType,
user: PropTypes.object,
});
|
779f1e2031419ea38bab1b616784a6685323a4a5
|
2023-11-17 02:24:48
|
Michelle Zhang
|
ref(feedback): always display feedback details if from alert (#60122)
| false
|
always display feedback details if from alert (#60122)
|
ref
|
diff --git a/static/app/components/feedback/useFeedbackOnboarding.tsx b/static/app/components/feedback/useFeedbackOnboarding.tsx
index 152816d8d66164..9dea1250ba551b 100644
--- a/static/app/components/feedback/useFeedbackOnboarding.tsx
+++ b/static/app/components/feedback/useFeedbackOnboarding.tsx
@@ -5,6 +5,7 @@ import {Project} from 'sentry/types';
import {PageFilters} from 'sentry/types/core';
import usePageFilters from 'sentry/utils/usePageFilters';
import useProjects from 'sentry/utils/useProjects';
+import useUrlParams from 'sentry/utils/useUrlParams';
function getSelectedProjectList(
selectedProjects: PageFilters['projects'],
@@ -45,3 +46,10 @@ export function useHaveSelectedProjectsSetupFeedback() {
fetching,
};
}
+
+export function useFeedbackHasSlug() {
+ const {getParamValue: getSlug} = useUrlParams('feedbackSlug', '');
+ const hasSlug = getSlug().length > 0;
+
+ return {hasSlug};
+}
diff --git a/static/app/views/feedback/feedbackListPage.tsx b/static/app/views/feedback/feedbackListPage.tsx
index 77e5d7f6bac2a9..adcf66abe2fdaa 100644
--- a/static/app/views/feedback/feedbackListPage.tsx
+++ b/static/app/views/feedback/feedbackListPage.tsx
@@ -9,7 +9,10 @@ import FeedbackItemLoader from 'sentry/components/feedback/feedbackItem/feedback
import FeedbackSearch from 'sentry/components/feedback/feedbackSearch';
import FeedbackSetupPanel from 'sentry/components/feedback/feedbackSetupPanel';
import FeedbackList from 'sentry/components/feedback/list/feedbackList';
-import {useHaveSelectedProjectsSetupFeedback} from 'sentry/components/feedback/useFeedbackOnboarding';
+import {
+ useFeedbackHasSlug,
+ useHaveSelectedProjectsSetupFeedback,
+} from 'sentry/components/feedback/useFeedbackOnboarding';
import {FeedbackQueryKeys} from 'sentry/components/feedback/useFeedbackQueryKeys';
import FullViewport from 'sentry/components/layouts/fullViewport';
import * as Layout from 'sentry/components/layouts/thirds';
@@ -29,6 +32,7 @@ interface Props extends RouteComponentProps<{}, {}, {}> {}
export default function FeedbackListPage({}: Props) {
const organization = useOrganization();
const {hasSetupOneFeedback} = useHaveSelectedProjectsSetupFeedback();
+ const {hasSlug} = useFeedbackHasSlug();
const location = useLocation();
return (
@@ -72,7 +76,7 @@ export default function FeedbackListPage({}: Props) {
<ErrorBoundary>
<LayoutGrid>
<FeedbackFilters style={{gridArea: 'filters'}} />
- {hasSetupOneFeedback ? (
+ {hasSetupOneFeedback || hasSlug ? (
<Fragment>
<Container style={{gridArea: 'list'}}>
<FeedbackList />
|
09ead9c81ab968657aa4eefe441869f3fa067774
|
2022-07-18 22:23:21
|
Nar Saynorath
|
feat(dashboard-filters): Add saved filter keys to type (#36762)
| false
|
Add saved filter keys to type (#36762)
|
feat
|
diff --git a/static/app/views/dashboardsV2/data.tsx b/static/app/views/dashboardsV2/data.tsx
index 18e169f78a6c9b..fb89cf5ea4cddf 100644
--- a/static/app/views/dashboardsV2/data.tsx
+++ b/static/app/views/dashboardsV2/data.tsx
@@ -13,6 +13,8 @@ export const EMPTY_DASHBOARD: DashboardDetails = {
createdBy: undefined,
title: t('Untitled dashboard'),
widgets: [],
+ projects: [],
+ filters: {},
};
export const DASHBOARDS_TEMPLATES: DashboardTemplate[] = [
@@ -22,6 +24,8 @@ export const DASHBOARDS_TEMPLATES: DashboardTemplate[] = [
createdBy: undefined,
title: t('General Template'),
description: t('Various Frontend and Backend Widgets'),
+ projects: [],
+ filters: {},
widgets: [
{
title: t('Number of Errors'),
@@ -383,6 +387,8 @@ export const DASHBOARDS_TEMPLATES: DashboardTemplate[] = [
dateCreated: '',
createdBy: undefined,
description: t('Erroring URLs and Web Vitals'),
+ projects: [],
+ filters: {},
widgets: [
{
title: t('Top 5 Issues by Unique Users Over Time'),
@@ -758,6 +764,8 @@ export const DASHBOARDS_TEMPLATES: DashboardTemplate[] = [
dateCreated: '',
createdBy: undefined,
description: t('Issues and Performance'),
+ projects: [],
+ filters: {},
widgets: [
{
title: t('Top 5 Issues by Unique Users Over Time'),
@@ -1121,6 +1129,8 @@ export const DASHBOARDS_TEMPLATES: DashboardTemplate[] = [
dateCreated: '',
createdBy: undefined,
description: t('Crash Details and Performance Vitals'),
+ projects: [],
+ filters: {},
widgets: [
{
title: t('Total Crashes'),
diff --git a/static/app/views/dashboardsV2/types.tsx b/static/app/views/dashboardsV2/types.tsx
index f67495b1ac1987..5df687e329881d 100644
--- a/static/app/views/dashboardsV2/types.tsx
+++ b/static/app/views/dashboardsV2/types.tsx
@@ -81,10 +81,18 @@ export type DashboardListItem = {
*/
export type DashboardDetails = {
dateCreated: string;
+ filters: {
+ releases?: string[];
+ };
id: string;
+ projects: number[];
title: string;
widgets: Widget[];
createdBy?: User;
+ end?: string;
+ environment?: string[];
+ period?: string;
+ start?: string;
};
export enum DashboardState {
diff --git a/tests/js/spec/components/modals/addToDashboardModal.spec.tsx b/tests/js/spec/components/modals/addToDashboardModal.spec.tsx
index f1faa78da962a7..6e02c18bd20780 100644
--- a/tests/js/spec/components/modals/addToDashboardModal.spec.tsx
+++ b/tests/js/spec/components/modals/addToDashboardModal.spec.tsx
@@ -37,6 +37,8 @@ describe('add to dashboard modal', () => {
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
};
let widget = {
title: 'Test title',
diff --git a/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
index 4518051727a90c..5dd8bac5cb0c26 100644
--- a/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/dashboard.spec.tsx
@@ -13,6 +13,8 @@ describe('Dashboards > Dashboard', () => {
id: '1',
title: 'Test Dashboard',
widgets: [],
+ projects: [],
+ filters: {},
};
const newWidget = {
title: 'Test Query',
diff --git a/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx b/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
index 7c1040d58379d6..cfc4f2d4f807e9 100644
--- a/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/gridLayout/dashboard.spec.tsx
@@ -18,6 +18,8 @@ describe('Dashboards > Dashboard', () => {
id: '1',
title: 'Test Dashboard',
widgets: [],
+ projects: [],
+ filters: {},
};
const newWidget: Widget = {
id: '1',
diff --git a/tests/js/spec/views/dashboardsV2/widgetBuilder/buildSteps/visualizationStep.spec.tsx b/tests/js/spec/views/dashboardsV2/widgetBuilder/buildSteps/visualizationStep.spec.tsx
index d27a923e11076a..94046d2d8a4666 100644
--- a/tests/js/spec/views/dashboardsV2/widgetBuilder/buildSteps/visualizationStep.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/widgetBuilder/buildSteps/visualizationStep.spec.tsx
@@ -83,6 +83,8 @@ describe('VisualizationStep', function () {
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
}}
onSave={jest.fn()}
params={{
@@ -132,6 +134,8 @@ describe('VisualizationStep', function () {
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
}}
onSave={jest.fn()}
params={{
diff --git a/tests/js/spec/views/dashboardsV2/widgetBuilder/widgetBuilder.spec.tsx b/tests/js/spec/views/dashboardsV2/widgetBuilder/widgetBuilder.spec.tsx
index 21d02e2ee5b965..05524e144bfea3 100644
--- a/tests/js/spec/views/dashboardsV2/widgetBuilder/widgetBuilder.spec.tsx
+++ b/tests/js/spec/views/dashboardsV2/widgetBuilder/widgetBuilder.spec.tsx
@@ -29,6 +29,19 @@ const defaultOrgFeatures = [
// Mocking worldMapChart to avoid act warnings
jest.mock('sentry/components/charts/worldMapChart');
+function mockDashboard(dashboard: Partial<DashboardDetails>): DashboardDetails {
+ return {
+ id: '1',
+ title: 'Dashboard',
+ createdBy: undefined,
+ dateCreated: '2020-01-01T00:00:00.000Z',
+ widgets: [],
+ projects: [],
+ filters: {},
+ ...dashboard,
+ };
+}
+
function renderTestComponent({
dashboard,
query,
@@ -70,6 +83,8 @@ function renderTestComponent({
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
...dashboard,
}}
onSave={onSave ?? jest.fn()}
@@ -95,6 +110,8 @@ describe('WidgetBuilder', function () {
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
};
const testDashboard: DashboardDetails = {
@@ -103,6 +120,8 @@ describe('WidgetBuilder', function () {
createdBy: undefined,
dateCreated: '2020-01-01T00:00:00.000Z',
widgets: [],
+ projects: [],
+ filters: {},
};
let eventsStatsMock: jest.Mock | undefined;
@@ -264,13 +283,7 @@ describe('WidgetBuilder', function () {
id: '1',
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -303,13 +316,7 @@ describe('WidgetBuilder', function () {
id: '1',
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -673,13 +680,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({dashboard, params: {widgetIndex: '0'}});
@@ -755,13 +756,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
const handleSave = jest.fn();
@@ -812,13 +807,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({dashboard, params: {widgetIndex: '0'}});
@@ -855,13 +844,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
const handleSave = jest.fn();
@@ -1006,13 +989,8 @@ describe('WidgetBuilder', function () {
},
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({onSave: handleSave, dashboard, params: {widgetIndex: '0'}});
@@ -1046,13 +1024,8 @@ describe('WidgetBuilder', function () {
},
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+
+ const dashboard = mockDashboard({widgets: [widget]});
const {router} = renderTestComponent({
dashboard,
@@ -1096,13 +1069,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
const handleSave = jest.fn();
@@ -1379,13 +1346,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -1439,13 +1400,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -1490,13 +1445,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -1720,13 +1669,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
query: {
@@ -1907,13 +1850,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -1945,13 +1882,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -2038,13 +1969,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -2216,13 +2141,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [...defaultOrgFeatures, 'new-widget-builder-experience-design'],
@@ -2782,13 +2701,7 @@ describe('WidgetBuilder', function () {
id: '1',
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: releaseHealthFeatureFlags,
@@ -3110,13 +3023,7 @@ describe('WidgetBuilder', function () {
id: '1',
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -3159,13 +3066,7 @@ describe('WidgetBuilder', function () {
limit: 1,
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -3208,13 +3109,7 @@ describe('WidgetBuilder', function () {
limit: 1,
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
dashboard,
@@ -3298,13 +3193,7 @@ describe('WidgetBuilder', function () {
],
};
- const dashboard: DashboardDetails = {
- id: '1',
- title: 'Dashboard',
- createdBy: undefined,
- dateCreated: '2020-01-01T00:00:00.000Z',
- widgets: [widget],
- };
+ const dashboard = mockDashboard({widgets: [widget]});
renderTestComponent({
orgFeatures: [
|
d9852118bdf20a09a2ba8d7eb612b4e03186468c
|
2020-04-09 20:56:16
|
MeredithAnya
|
ref(integrations): Add sentry APM to ApiClient (#17792)
| false
|
Add sentry APM to ApiClient (#17792)
|
ref
|
diff --git a/src/sentry/api/endpoints/group_integration_details.py b/src/sentry/api/endpoints/group_integration_details.py
index 9877a157cbf9bd..4f9133b1f5054a 100644
--- a/src/sentry/api/endpoints/group_integration_details.py
+++ b/src/sentry/api/endpoints/group_integration_details.py
@@ -12,6 +12,8 @@
from sentry.shared_integrations.exceptions import IntegrationError, IntegrationFormError
from sentry.models import Activity, ExternalIssue, GroupLink, Integration
from sentry.signals import integration_issue_created, integration_issue_linked
+from sentry.web.decorators import transaction_start
+
MISSING_FEATURE_MESSAGE = "Your organization does not have access to this feature."
@@ -43,6 +45,7 @@ def create_issue_activity(self, request, group, installation, external_issue):
data=issue_information,
)
+ @transaction_start("GroupIntegrationDetailsEndpoint")
def get(self, request, group, integration_id):
if not self._has_issue_feature(group.organization, request.user):
return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400)
@@ -81,6 +84,7 @@ def get(self, request, group, integration_id):
return Response({"detail": six.text_type(e)}, status=400)
# was thinking put for link an existing issue, post for create new issue?
+ @transaction_start("GroupIntegrationDetailsEndpoint")
def put(self, request, group, integration_id):
if not self._has_issue_feature(group.organization, request.user):
return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400)
@@ -169,6 +173,7 @@ def put(self, request, group, integration_id):
}
return Response(context, status=201)
+ @transaction_start("GroupIntegrationDetailsEndpoint")
def post(self, request, group, integration_id):
if not self._has_issue_feature(group.organization, request.user):
return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400)
@@ -241,6 +246,7 @@ def post(self, request, group, integration_id):
}
return Response(context, status=201)
+ @transaction_start("GroupIntegrationDetailsEndpoint")
def delete(self, request, group, integration_id):
if not self._has_issue_feature(group.organization, request.user):
return Response({"detail": MISSING_FEATURE_MESSAGE}, status=400)
diff --git a/src/sentry/integrations/client.py b/src/sentry/integrations/client.py
index 9655f21d5d53f0..6f79fdb3856eb7 100644
--- a/src/sentry/integrations/client.py
+++ b/src/sentry/integrations/client.py
@@ -1,9 +1,7 @@
from __future__ import absolute_import
-
from time import time
-
from sentry.shared_integrations.client import BaseApiClient
from sentry.exceptions import InvalidIdentity
diff --git a/src/sentry/shared_integrations/client.py b/src/sentry/shared_integrations/client.py
index 86021fed26cd99..1424ab32283c34 100644
--- a/src/sentry/shared_integrations/client.py
+++ b/src/sentry/shared_integrations/client.py
@@ -3,6 +3,7 @@
import logging
import json
import requests
+import sentry_sdk
import six
from collections import OrderedDict
@@ -147,13 +148,16 @@ def name(cls):
def get_cache_prefix(self):
return u"%s.%s.client:" % (self.integration_type, self.name)
- def track_response_data(self, code, error=None):
+ def track_response_data(self, code, span, error=None):
metrics.incr(
u"%s.http_response" % (self.datadog_prefix),
sample_rate=1.0,
tags={self.integration_type: self.name, "status": code},
)
+ span.set_http_status(code)
+ span.set_tag(self.integration_type, self.name)
+
extra = {
self.integration_type: self.name,
"status_string": six.text_type(code),
@@ -203,42 +207,47 @@ def _request(
sample_rate=1.0,
tags={self.integration_type: self.name},
)
- try:
- resp = getattr(session, method.lower())(
- url=full_url,
- headers=headers,
- json=data if json else None,
- data=data if not json else None,
- params=params,
- auth=auth,
- verify=self.verify_ssl,
- allow_redirects=allow_redirects,
- timeout=timeout,
- )
- resp.raise_for_status()
- except ConnectionError as e:
- self.track_response_data("connection_error", e)
- raise ApiHostError.from_exception(e)
- except Timeout as e:
- self.track_response_data("timeout", e)
- raise ApiTimeoutError.from_exception(e)
- except HTTPError as e:
- resp = e.response
- if resp is None:
- self.track_response_data("unknown", e)
- self.logger.exception(
- "request.error", extra={self.integration_type: self.name, "url": full_url}
+
+ with sentry_sdk.start_span(
+ op=u"{}.http".format(self.integration_type),
+ transaction=u"{}.http_response.{}".format(self.integration_type, self.name),
+ ) as span:
+ try:
+ resp = getattr(session, method.lower())(
+ url=full_url,
+ headers=headers,
+ json=data if json else None,
+ data=data if not json else None,
+ params=params,
+ auth=auth,
+ verify=self.verify_ssl,
+ allow_redirects=allow_redirects,
+ timeout=timeout,
)
- raise ApiError("Internal Error")
- self.track_response_data(resp.status_code, e)
- raise ApiError.from_response(resp)
+ resp.raise_for_status()
+ except ConnectionError as e:
+ self.track_response_data("connection_error", span, e)
+ raise ApiHostError.from_exception(e)
+ except Timeout as e:
+ self.track_response_data("timeout", span, e)
+ raise ApiTimeoutError.from_exception(e)
+ except HTTPError as e:
+ resp = e.response
+ if resp is None:
+ self.track_response_data("unknown", span, e)
+ self.logger.exception(
+ "request.error", extra={self.integration_type: self.name, "url": full_url}
+ )
+ raise ApiError("Internal Error")
+ self.track_response_data(resp.status_code, span, e)
+ raise ApiError.from_response(resp)
- self.track_response_data(resp.status_code)
+ self.track_response_data(resp.status_code, span)
- if resp.status_code == 204:
- return {}
+ if resp.status_code == 204:
+ return {}
- return BaseApiResponse.from_response(resp, allow_text=allow_text)
+ return BaseApiResponse.from_response(resp, allow_text=allow_text)
# subclasses should override ``request``
def request(self, *args, **kwargs):
diff --git a/src/sentry/tasks/post_process.py b/src/sentry/tasks/post_process.py
index d62b4f9eef58e2..1358d7fd7f6656 100644
--- a/src/sentry/tasks/post_process.py
+++ b/src/sentry/tasks/post_process.py
@@ -2,8 +2,10 @@
import logging
import time
+import sentry_sdk
from django.conf import settings
+from sentry_sdk.tracing import Span
from sentry import features
from sentry.utils.cache import cache
@@ -177,7 +179,10 @@ def post_process_group(event, is_new, is_regression, is_new_group_environment, *
# objects back and forth isn't super efficient
for callback, futures in rp.apply():
has_alert = True
- safe_execute(callback, event, futures)
+ with sentry_sdk.start_span(
+ Span(op="post_process_group", transaction="rule_processor_apply", sampled=True)
+ ):
+ safe_execute(callback, event, futures)
if features.has("projects:servicehooks", project=event.project):
allowed_events = set(["event.created"])
diff --git a/src/sentry/web/decorators.py b/src/sentry/web/decorators.py
index 297a5f40201e2c..939842a256bd02 100644
--- a/src/sentry/web/decorators.py
+++ b/src/sentry/web/decorators.py
@@ -7,6 +7,8 @@
from django.utils.translation import ugettext_lazy as _
from sentry.utils import auth
+from sentry_sdk import Hub
+from sentry_sdk.tracing import Span
ERR_BAD_SIGNATURE = _("The link you followed is invalid or expired.")
@@ -37,3 +39,15 @@ def wrapped(request, *args, **kwargs):
return func(request, *args, **kwargs)
return wrapped
+
+
+def transaction_start(endpoint):
+ def decorator(func):
+ @wraps(func)
+ def wrapped(request, *args, **kwargs):
+ with Hub.current.start_span(Span(op="http.server", transaction=endpoint, sampled=True)):
+ return func(request, *args, **kwargs)
+
+ return wrapped
+
+ return decorator
diff --git a/tests/integration/tests.py b/tests/integration/tests.py
index cca70a8f1fcb9a..2398f248882c71 100644
--- a/tests/integration/tests.py
+++ b/tests/integration/tests.py
@@ -525,7 +525,9 @@ def new_disable_transaction_events():
body = "".join(app_iter)
assert status == "200 OK", body
- assert not events
+ assert set((e.get("type"), e.get("transaction")) for e in events) == {
+ ("transaction", "rule_processor_apply")
+ }
assert calls == [1]
|
cc4ea1dade2029046c32c85cbc7c86d16a2ff38e
|
2022-02-23 16:10:33
|
Neel Shah
|
chore: Update pip dependabot reviewer to team-web-backend (#31990)
| false
|
Update pip dependabot reviewer to team-web-backend (#31990)
|
chore
|
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
index b107876069ebb4..e5f74fc11a2f23 100644
--- a/.github/dependabot.yml
+++ b/.github/dependabot.yml
@@ -97,6 +97,6 @@ updates:
timezone: America/Los_Angeles
time: "09:00"
reviewers:
- - "@getsentry/team-webplatform"
+ - "@getsentry/team-web-backend"
allow:
- dependency-name: "sentry-sdk"
|
999ee603998f2ae2881c875d6288a922f33a202e
|
2024-05-04 01:05:25
|
edwardgou-sentry
|
fix(performance): Fixes samples table always showing scroll bar in the webvitals module (#70268)
| false
|
Fixes samples table always showing scroll bar in the webvitals module (#70268)
|
fix
|
diff --git a/static/app/views/performance/browser/webVitals/pageSamplePerformanceTable.tsx b/static/app/views/performance/browser/webVitals/pageSamplePerformanceTable.tsx
index 1a2331c9dc92ba..ebbd6a2e04c605 100644
--- a/static/app/views/performance/browser/webVitals/pageSamplePerformanceTable.tsx
+++ b/static/app/views/performance/browser/webVitals/pageSamplePerformanceTable.tsx
@@ -463,36 +463,34 @@ export function PageSamplePerformanceTable({transaction, search, limit = 9}: Pro
</Wrapper>
)}
</SearchBarContainer>
- <GridContainer>
- {datatype === Datatype.PAGELOADS && (
- <GridEditable
- isLoading={isLoading}
- columnOrder={PAGELOADS_COLUMN_ORDER}
- columnSortBy={[]}
- data={tableData}
- grid={{
- renderHeadCell,
- renderBodyCell,
- }}
- location={location}
- minimumColWidth={70}
- />
- )}
- {datatype === Datatype.INTERACTIONS && (
- <GridEditable
- isLoading={isInteractionsLoading}
- columnOrder={INTERACTION_SAMPLES_COLUMN_ORDER}
- columnSortBy={[]}
- data={interactionsTableData}
- grid={{
- renderHeadCell,
- renderBodyCell,
- }}
- location={location}
- minimumColWidth={70}
- />
- )}
- </GridContainer>
+ {datatype === Datatype.PAGELOADS && (
+ <GridEditable
+ isLoading={isLoading}
+ columnOrder={PAGELOADS_COLUMN_ORDER}
+ columnSortBy={[]}
+ data={tableData}
+ grid={{
+ renderHeadCell,
+ renderBodyCell,
+ }}
+ location={location}
+ minimumColWidth={70}
+ />
+ )}
+ {datatype === Datatype.INTERACTIONS && (
+ <GridEditable
+ isLoading={isInteractionsLoading}
+ columnOrder={INTERACTION_SAMPLES_COLUMN_ORDER}
+ columnSortBy={[]}
+ data={interactionsTableData}
+ grid={{
+ renderHeadCell,
+ renderBodyCell,
+ }}
+ location={location}
+ minimumColWidth={70}
+ />
+ )}
</span>
);
}
@@ -522,28 +520,6 @@ const StyledProjectAvatar = styled(ProjectAvatar)`
padding-right: ${space(1)};
`;
-// Not pretty but we need to override gridEditable styles since the original
-// styles have too much padding for small spaces
-const GridContainer = styled('div')`
- margin-bottom: ${space(1)};
- th {
- padding: 0 ${space(1)};
- }
- th:first-child {
- padding-left: ${space(2)};
- }
- th:last-child {
- padding-right: ${space(2)};
- }
- td {
- padding: ${space(1)};
- }
- td:first-child {
- padding-right: ${space(1)};
- padding-left: ${space(2)};
- }
-`;
-
const NoValue = styled('span')`
color: ${p => p.theme.gray300};
`;
|
609c2bb0edccc0c7efbafa4ffff956a404608468
|
2024-12-05 01:03:47
|
Snigdha Sharma
|
chore(seer-severity): Log seer severity errors to sentry (#81681)
| false
|
Log seer severity errors to sentry (#81681)
|
chore
|
diff --git a/src/sentry/event_manager.py b/src/sentry/event_manager.py
index 4f5520ecdfd80f..bbb6d1dd9b3a07 100644
--- a/src/sentry/event_manager.py
+++ b/src/sentry/event_manager.py
@@ -2119,14 +2119,17 @@ def _get_severity_score(event: Event) -> tuple[float, str]:
reason = "microservice_max_retry"
update_severity_error_count()
metrics.incr("issues.severity.error", tags={"reason": "max_retries"})
+ logger.exception("Seer severity microservice max retries exceeded")
except TimeoutError:
reason = "microservice_timeout"
update_severity_error_count()
metrics.incr("issues.severity.error", tags={"reason": "timeout"})
+ logger.exception("Seer severity microservice timeout")
except Exception:
reason = "microservice_error"
update_severity_error_count()
metrics.incr("issues.severity.error", tags={"reason": "unknown"})
+ logger.exception("Seer severity microservice error")
sentry_sdk.capture_exception()
else:
update_severity_error_count(reset=True)
|
6c2d19c0b876bbf9de66b68c683dfc6b4891dd4a
|
2020-03-24 10:42:03
|
Matej Minar
|
feat(ui): Add titles to individual tabs in release v2 detail (#17819)
| false
|
Add titles to individual tabs in release v2 detail (#17819)
|
feat
|
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/artifacts/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/artifacts/index.tsx
index a746a2c8eb7d3f..27f9f8dfcab385 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/artifacts/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/artifacts/index.tsx
@@ -1,23 +1,45 @@
import React from 'react';
import styled from '@emotion/styled';
-import {Params} from 'react-router/lib/Router';
-import {Location} from 'history';
+import {RouteComponentProps} from 'react-router/lib/Router';
import {t} from 'app/locale';
import Alert from 'app/components/alert';
import space from 'app/styles/space';
import ReleaseArtifactsV1 from 'app/views/releases/detail/releaseArtifacts';
+import AsyncView from 'app/views/asyncView';
+import routeTitleGen from 'app/utils/routeTitle';
+import {formatVersion} from 'app/utils/formatters';
+import withOrganization from 'app/utils/withOrganization';
+import {Organization} from 'app/types';
import {ReleaseContext} from '..';
-type Props = {
- params: Params;
- location: Location;
+type RouteParams = {
+ orgId: string;
+ release: string;
};
-const ReleaseArtifacts = ({params, location}: Props) => (
- <ReleaseContext.Consumer>
- {({project}) => (
+type Props = RouteComponentProps<RouteParams, {}> & {
+ organization: Organization;
+};
+
+class ReleaseArtifacts extends AsyncView<Props> {
+ static contextType = ReleaseContext;
+
+ getTitle() {
+ const {params, organization} = this.props;
+ return routeTitleGen(
+ t('Artifacts - Release %s', formatVersion(params.release)),
+ organization.slug,
+ false
+ );
+ }
+
+ renderBody() {
+ const {project} = this.context;
+ const {params, location} = this.props;
+
+ return (
<ContentBox>
<Alert type="warning">
{t(
@@ -32,9 +54,9 @@ const ReleaseArtifacts = ({params, location}: Props) => (
smallEmptyMessage
/>
</ContentBox>
- )}
- </ReleaseContext.Consumer>
-);
+ );
+ }
+}
const ContentBox = styled('div')`
padding: ${space(4)};
@@ -42,4 +64,4 @@ const ContentBox = styled('div')`
background-color: ${p => p.theme.white};
`;
-export default ReleaseArtifacts;
+export default withOrganization(ReleaseArtifacts);
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/commits/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/commits/index.tsx
index 2bb032e037934e..6a124b606ffda8 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/commits/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/commits/index.tsx
@@ -6,11 +6,15 @@ import AsyncComponent from 'app/components/asyncComponent';
import CommitRow from 'app/components/commitRow';
import {t} from 'app/locale';
import space from 'app/styles/space';
-import {Repository, Commit} from 'app/types';
+import {Repository, Commit, Organization} from 'app/types';
import EmptyStateWarning from 'app/components/emptyStateWarning';
import {PanelHeader, Panel, PanelBody} from 'app/components/panels';
import DropdownControl, {DropdownItem} from 'app/components/dropdownControl';
import overflowEllipsisLeft from 'app/styles/overflowEllipsisLeft';
+import AsyncView from 'app/views/asyncView';
+import routeTitleGen from 'app/utils/routeTitle';
+import {formatVersion} from 'app/utils/formatters';
+import withOrganization from 'app/utils/withOrganization';
import {getCommitsByRepository, CommitsByRepository} from '../utils';
import ReleaseNoCommitData from '../releaseNoCommitData';
@@ -23,7 +27,9 @@ type RouteParams = {
release: string;
};
-type Props = RouteComponentProps<RouteParams, {}>;
+type Props = RouteComponentProps<RouteParams, {}> & {
+ organization: Organization;
+};
type State = {
commits: Commit[];
@@ -31,9 +37,18 @@ type State = {
activeRepo: string;
} & AsyncComponent['state'];
-class ReleaseCommits extends AsyncComponent<Props, State> {
+class ReleaseCommits extends AsyncView<Props, State> {
static contextType = ReleaseContext;
+ getTitle() {
+ const {params, organization} = this.props;
+ return routeTitleGen(
+ t('Commits - Release %s', formatVersion(params.release)),
+ organization.slug,
+ false
+ );
+ }
+
getDefaultState() {
return {
...super.getDefaultState(),
@@ -161,4 +176,4 @@ const RepoLabel = styled('div')`
${overflowEllipsisLeft}
`;
-export default ReleaseCommits;
+export default withOrganization(ReleaseCommits);
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/filesChanged/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/filesChanged/index.tsx
index b9062e437e01e1..59ea967ef11b7e 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/filesChanged/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/filesChanged/index.tsx
@@ -1,28 +1,46 @@
import React from 'react';
-import {Params} from 'react-router/lib/Router';
+import {RouteComponentProps} from 'react-router/lib/Router';
import styled from '@emotion/styled';
import AsyncComponent from 'app/components/asyncComponent';
import RepositoryFileSummary from 'app/components/repositoryFileSummary';
import {t} from 'app/locale';
import space from 'app/styles/space';
-import {CommitFile, Repository} from 'app/types';
+import {CommitFile, Repository, Organization} from 'app/types';
import EmptyStateWarning from 'app/components/emptyStateWarning';
+import AsyncView from 'app/views/asyncView';
+import withOrganization from 'app/utils/withOrganization';
+import routeTitleGen from 'app/utils/routeTitle';
+import {formatVersion} from 'app/utils/formatters';
import {Panel, PanelBody} from 'app/components/panels';
import {getFilesByRepository} from '../utils';
import ReleaseNoCommitData from '../releaseNoCommitData';
-type Props = {
- params: Params;
-} & AsyncComponent['props'];
+type RouteParams = {
+ orgId: string;
+ release: string;
+};
+
+type Props = RouteComponentProps<RouteParams, {}> & {
+ organization: Organization;
+};
type State = {
fileList: CommitFile[];
repos: Repository[];
} & AsyncComponent['state'];
-class FilesChanged extends AsyncComponent<Props, State> {
+class FilesChanged extends AsyncView<Props, State> {
+ getTitle() {
+ const {params, organization} = this.props;
+ return routeTitleGen(
+ t('Files Changed - Release %s', formatVersion(params.release)),
+ organization.slug,
+ false
+ );
+ }
+
getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
const {orgId, release} = this.props.params;
@@ -80,4 +98,4 @@ const ContentBox = styled('div')`
}
`;
-export default FilesChanged;
+export default withOrganization(FilesChanged);
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
index e0fd5c787938bf..7ae445ee47df1c 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/index.tsx
@@ -1,7 +1,5 @@
import React from 'react';
-import * as ReactRouter from 'react-router';
-import {Params} from 'react-router/lib/Router';
-import {Location} from 'history';
+import {RouteComponentProps} from 'react-router/lib/Router';
import pick from 'lodash/pick';
import styled from '@emotion/styled';
@@ -23,13 +21,15 @@ import ReleaseHeader from './releaseHeader';
type ReleaseContext = {release: Release; project: ReleaseProject};
const ReleaseContext = React.createContext<ReleaseContext>({} as ReleaseContext);
-type Props = {
+type RouteParams = {
+ orgId: string;
+ release: string;
+};
+
+type Props = RouteComponentProps<RouteParams, {}> & {
organization: Organization;
- location: Location;
- router: ReactRouter.InjectedRouter;
- params: Params;
selection: GlobalSelection;
-} & AsyncView['props'];
+};
type State = {
release: Release;
diff --git a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/index.tsx
index 935a6f838b042d..8e0dea079da756 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/detail/overview/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/detail/overview/index.tsx
@@ -1,14 +1,17 @@
import React from 'react';
import styled from '@emotion/styled';
-import {Params, InjectedRouter} from 'react-router/lib/Router';
-import {Location} from 'history';
+import {RouteComponentProps} from 'react-router/lib/Router';
+import {t} from 'app/locale';
+import AsyncView from 'app/views/asyncView';
import withOrganization from 'app/utils/withOrganization';
import withGlobalSelection from 'app/utils/withGlobalSelection';
import {Organization, GlobalSelection} from 'app/types';
import space from 'app/styles/space';
import {Client} from 'app/api';
import withApi from 'app/utils/withApi';
+import {formatVersion} from 'app/utils/formatters';
+import routeTitleGen from 'app/utils/routeTitle';
import ReleaseChartContainer from './chart';
import Issues from './issues';
@@ -20,23 +23,37 @@ import {YAxis} from './chart/releaseChartControls';
import {ReleaseContext} from '..';
-type Props = {
+type RouteParams = {
+ orgId: string;
+ release: string;
+};
+
+type Props = RouteComponentProps<RouteParams, {}> & {
organization: Organization;
- params: Params;
- location: Location;
selection: GlobalSelection;
- router: InjectedRouter;
api: Client;
};
type State = {
yAxis: YAxis;
-};
+} & AsyncView['state'];
-class ReleaseOverview extends React.Component<Props, State> {
- state: State = {
- yAxis: 'sessions',
- };
+class ReleaseOverview extends AsyncView<Props, State> {
+ getTitle() {
+ const {params, organization} = this.props;
+ return routeTitleGen(
+ t('Release %s', formatVersion(params.release)),
+ organization.slug,
+ false
+ );
+ }
+
+ getDefaultState() {
+ return {
+ ...super.getDefaultState(),
+ yAxis: 'sessions',
+ };
+ }
handleYAxisChange = (yAxis: YAxis) => {
this.setState({yAxis});
diff --git a/src/sentry/static/sentry/app/views/releasesV2/list/index.tsx b/src/sentry/static/sentry/app/views/releasesV2/list/index.tsx
index 5be0a9f012b14a..bdbfe4eb140095 100644
--- a/src/sentry/static/sentry/app/views/releasesV2/list/index.tsx
+++ b/src/sentry/static/sentry/app/views/releasesV2/list/index.tsx
@@ -1,7 +1,5 @@
import React from 'react';
-import {Location} from 'history';
-import * as ReactRouter from 'react-router';
-import {Params} from 'react-router/lib/Router';
+import {RouteComponentProps} from 'react-router/lib/Router';
import styled from '@emotion/styled';
import pick from 'lodash/pick';
@@ -28,12 +26,13 @@ import {DEFAULT_STATS_PERIOD} from 'app/constants';
import ReleaseListSortOptions from './releaseListSortOptions';
-type Props = {
- params: Params;
- location: Location;
+type RouteParams = {
+ orgId: string;
+};
+
+type Props = RouteComponentProps<RouteParams, {}> & {
organization: Organization;
- router: ReactRouter.InjectedRouter;
-} & AsyncView['props'];
+};
type State = AsyncView['state'];
|
338b42d8c0be4a4fe3680cbf21fbc1e4dfd31223
|
2022-02-23 15:30:17
|
Jonas
|
feat(flamegraph): select a thread (#31865)
| false
|
select a thread (#31865)
|
feat
|
diff --git a/docs-ui/stories/components/profiling/flamegraphZoomView.stories.js b/docs-ui/stories/components/profiling/flamegraphZoomView.stories.js
index b839defb6095e7..434c42af9081f1 100644
--- a/docs-ui/stories/components/profiling/flamegraphZoomView.stories.js
+++ b/docs-ui/stories/components/profiling/flamegraphZoomView.stories.js
@@ -2,10 +2,12 @@ import * as React from 'react';
import {FlamegraphOptionsMenu} from 'sentry/components/profiling/FlamegraphOptionsMenu';
import {FlamegraphSearch} from 'sentry/components/profiling/FlamegraphSearch';
+import {FlamegraphToolbar} from 'sentry/components/profiling/FlamegraphToolbar';
import {FlamegraphViewSelectMenu} from 'sentry/components/profiling/FlamegraphViewSelectMenu';
import {FlamegraphZoomView} from 'sentry/components/profiling/FlamegraphZoomView';
import {FlamegraphZoomViewMinimap} from 'sentry/components/profiling/FlamegraphZoomViewMinimap';
import {ProfileDragDropImport} from 'sentry/components/profiling/ProfileDragDropImport';
+import {ThreadMenuSelector} from 'sentry/components/profiling/ThreadSelector';
import {CanvasPoolManager} from 'sentry/utils/profiling/canvasScheduler';
import {Flamegraph} from 'sentry/utils/profiling/flamegraph';
import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/FlamegraphThemeProvider';
@@ -38,6 +40,15 @@ export const EventedTrace = () => {
[view.inverted, view.leftHeavy]
);
+ const onProfileIndexChange = React.useCallback(
+ index => {
+ setFlamegraph(
+ new Flamegraph(profiles.profiles[index], index, view.inverted, view.leftHeavy)
+ );
+ },
+ [view.inverted, view.leftHeavy]
+ );
+
React.useEffect(() => {
setFlamegraph(new Flamegraph(profiles.profiles[0], 0, view.inverted, view.leftHeavy));
}, [view.inverted, view.leftHeavy]);
@@ -53,14 +64,7 @@ export const EventedTrace = () => {
overscrollBehavior: 'contain',
}}
>
- <div
- style={{
- display: 'flex',
- flexDirection: 'row',
- justifyContent: 'space-between',
- marginBottom: 8,
- }}
- >
+ <FlamegraphToolbar>
<FlamegraphViewSelectMenu
view={view.inverted ? 'bottom up' : 'top down'}
sorting={view.leftHeavy ? 'left heavy' : 'call order'}
@@ -71,6 +75,11 @@ export const EventedTrace = () => {
setView({...view, inverted: v === 'bottom up'});
}}
/>
+ <ThreadMenuSelector
+ profileGroup={profiles}
+ activeProfileIndex={flamegraph.profileIndex}
+ onProfileIndexChange={onProfileIndexChange}
+ />
<FlamegraphOptionsMenu
colorCoding={colorCoding}
onColorCodingChange={setColorCoding}
@@ -78,7 +87,8 @@ export const EventedTrace = () => {
onHighlightRecursionChange={setHighlightRecursion}
canvasPoolManager={canvasPoolManager}
/>
- </div>
+ <div />
+ </FlamegraphToolbar>
<div style={{height: 100, position: 'relative'}}>
<FlamegraphZoomViewMinimap
flamegraph={flamegraph}
diff --git a/static/app/components/autoComplete.tsx b/static/app/components/autoComplete.tsx
index 7982330c93c88b..c0131206970b2c 100644
--- a/static/app/components/autoComplete.tsx
+++ b/static/app/components/autoComplete.tsx
@@ -81,7 +81,7 @@ type Props<T> = typeof defaultProps & {
/**
* Must be a function that returns a component
*/
- children: (props: ChildrenProps<T>) => React.ReactElement;
+ children: (props: ChildrenProps<T>) => React.ReactElement | null;
disabled: boolean;
defaultHighlightedIndex?: number;
defaultInputValue?: string;
@@ -265,6 +265,15 @@ class AutoComplete<T extends Item> extends React.Component<Props<T>, State<T>> {
this.handleSelect(item, e);
};
+ handleItemMouseEnter =
+ ({item, index}: GetItemArgs<T>) =>
+ (_e: React.MouseEvent) => {
+ if (item.disabled) {
+ return;
+ }
+ this.setState({highlightedIndex: index});
+ };
+
handleMenuMouseDown = () => {
// Cancel close menu from input blur (mouseDown event can occur before input blur :()
setTimeout(() => {
@@ -377,6 +386,7 @@ class AutoComplete<T extends Item> extends React.Component<Props<T>, State<T>> {
...props,
'data-test-id': item['data-test-id'],
onClick: this.handleItemClick({item, index: newIndex, ...props}),
+ onMouseEnter: this.handleItemMouseEnter({item, index: newIndex, ...props}),
};
};
diff --git a/static/app/components/profiling/FlamegraphToolbar.tsx b/static/app/components/profiling/FlamegraphToolbar.tsx
new file mode 100644
index 00000000000000..7530376e23fdbd
--- /dev/null
+++ b/static/app/components/profiling/FlamegraphToolbar.tsx
@@ -0,0 +1,11 @@
+import styled from '@emotion/styled';
+
+interface FlamegraphToolbarProps {
+ children: React.ReactNode;
+}
+
+export const FlamegraphToolbar = styled('div')<FlamegraphToolbarProps>`
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+`;
diff --git a/static/app/components/profiling/ThreadSelector.tsx b/static/app/components/profiling/ThreadSelector.tsx
new file mode 100644
index 00000000000000..53be83b4a4de84
--- /dev/null
+++ b/static/app/components/profiling/ThreadSelector.tsx
@@ -0,0 +1,221 @@
+import * as React from 'react';
+import {css} from '@emotion/react';
+import styled from '@emotion/styled';
+import Fuse from 'fuse.js';
+
+import AutoComplete from 'sentry/components/autoComplete';
+import Button from 'sentry/components/button';
+import Input from 'sentry/components/forms/controls/input';
+import {IconCheckmark} from 'sentry/icons';
+import {t} from 'sentry/locale';
+import space from 'sentry/styles/space';
+import {ProfileGroup} from 'sentry/utils/profiling/profile/importProfile';
+import {Profile} from 'sentry/utils/profiling/profile/profile';
+import useOnClickOutside from 'sentry/utils/useOnClickOutside';
+
+const sortProfiles = (profiles: ReadonlyArray<Profile>): ProfileGroup['profiles'] => {
+ return [...profiles].sort((a, b) => {
+ if (!b.duration) {
+ return -1;
+ }
+ if (!a.duration) {
+ return 1;
+ }
+
+ if (a.name.startsWith('(tid') && b.name.startsWith('(tid')) {
+ return -1;
+ }
+ if (a.name.startsWith('(tid')) {
+ return -1;
+ }
+ if (b.name.startsWith('(tid')) {
+ return -1;
+ }
+ if (a.name.includes('main')) {
+ return -1;
+ }
+ if (b.name.includes('main')) {
+ return 1;
+ }
+ return a.name > b.name ? -1 : 1;
+ });
+};
+
+interface ThreadSelectorProps {
+ activeProfileIndex: ProfileGroup['activeProfileIndex'];
+ onProfileIndexChange: (index: number) => void;
+ profileGroup: ProfileGroup;
+}
+
+function ThreadMenuSelector(props: ThreadSelectorProps): React.ReactElement | null {
+ const containerRef = React.useRef<HTMLDivElement>(null);
+ const [open, setOpen] = React.useState<boolean>(false);
+
+ const handleSelectItem = React.useCallback(
+ (p: Fuse.FuseResultWithMatches<Profile & {index: number}>) => {
+ const index = props.profileGroup.profiles.findIndex(
+ profile => profile.name === p.item.name
+ );
+ if (index === -1) {
+ return;
+ }
+ props.onProfileIndexChange(index);
+ },
+ [props.onProfileIndexChange, props.profileGroup]
+ );
+
+ React.useEffect(() => {
+ const tagNamesToPreventStealingFocusFrom = new Set<Element['tagName']>([
+ 'INPUT',
+ 'TEXTAREA',
+ ]);
+ function handleKeyDown(evt) {
+ if (tagNamesToPreventStealingFocusFrom.has(evt.target.tagName)) {
+ return;
+ }
+ if (evt.key === 't' && !open) {
+ evt.preventDefault();
+ setOpen(true);
+ }
+ if (evt.key === 'Escape' && open) {
+ setOpen(false);
+ }
+ }
+
+ document.addEventListener('keydown', handleKeyDown);
+ return () => document.removeEventListener('keydown', handleKeyDown);
+ }, [open]);
+
+ useOnClickOutside(containerRef, () => {
+ setOpen(false);
+ });
+
+ return (
+ <div>
+ <Button size="zero" borderless onClick={() => setOpen(true)}>
+ {props.profileGroup.profiles[props.activeProfileIndex]?.name ??
+ t('Select Thread')}
+ </Button>
+ <AutoComplete
+ // @ts-ignore the type is typed as any
+ onSelect={handleSelectItem}
+ closeOnSelect={false}
+ isOpen={open}
+ >
+ {({getInputProps, getItemProps, isOpen, inputValue, highlightedIndex}) => {
+ const sortedProfiles = sortProfiles(props.profileGroup.profiles);
+ const filteredProfiles = inputValue
+ ? new Fuse(sortedProfiles, {includeMatches: true, keys: ['name']}).search(
+ inputValue
+ )
+ : sortedProfiles.map(p => ({item: p, matches: [], score: 1}));
+
+ return isOpen ? (
+ <ThreadSelectorContainer ref={containerRef}>
+ <Input
+ type="search"
+ autoFocus
+ {...getInputProps({
+ onKeyDown: evt => {
+ if (evt.key === 'Escape') {
+ setOpen(false);
+ }
+ },
+ })}
+ />
+ <DropdownBox>
+ {filteredProfiles.length > 0 ? (
+ filteredProfiles.map((profile, index) => {
+ const activeProfile =
+ props.profileGroup.profiles[props.activeProfileIndex];
+
+ return (
+ <SearchResult
+ key={index}
+ highlighted={index === highlightedIndex}
+ ref={ref =>
+ index === highlightedIndex
+ ? ref?.scrollIntoView({block: 'nearest'})
+ : null
+ }
+ {...getItemProps({
+ // @ts-ignore the type is typed as any
+ item: profile,
+ index,
+ })}
+ >
+ {activeProfile.name === profile.item.name ? (
+ <IconCheckmark size="sm" style={{marginRight: space(1)}} />
+ ) : null}
+ {profile.item.name}
+ </SearchResult>
+ );
+ })
+ ) : (
+ <EmptyItem>{t('No results found')}</EmptyItem>
+ )}
+ </DropdownBox>
+ </ThreadSelectorContainer>
+ ) : null;
+ }}
+ </AutoComplete>
+ </div>
+ );
+}
+
+const SearchResult = styled('li')<{highlighted: boolean}>`
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ color: ${p => p.theme.textColor};
+ padding: ${space(1)} ${space(2)};
+
+ ${p =>
+ p.highlighted &&
+ css`
+ color: ${p.theme.purple300};
+ background: ${p.theme.backgroundSecondary};
+ `};
+
+ &:not(:first-child) {
+ border-top: 1px solid ${p => p.theme.innerBorder};
+ }
+`;
+
+const EmptyItem = styled('li')`
+ text-align: center;
+ padding: 16px;
+ opacity: 0.5;
+`;
+
+const DropdownBox = styled('ul')`
+ list-style-type: none;
+ padding: 0;
+ background: ${p => p.theme.background};
+ border: 1px solid ${p => p.theme.border};
+ box-shadow: ${p => p.theme.dropShadowHeavy};
+ right: 0;
+ width: 100%;
+ max-height: 60vh;
+ border-radius: 5px;
+ position: absolute;
+ overflow-y: auto;
+ top: 40px;
+`;
+
+const ThreadSelectorContainer = styled('div')`
+ z-index: ${p => p.theme.zIndex.dropdown};
+ border-radius: ${p => p.theme.borderRadius};
+ position: absolute;
+ max-width: 540px;
+ overflow: auto;
+ display: flex;
+ flex-direction: column;
+ width: 50%;
+ height: 80vh;
+ left: 50%;
+ transform: translate(-50%, 0);
+ top: 60px;
+`;
+
+export {ThreadMenuSelector};
|
b1eeda9f6bfce9f47696ce50233cd03c4e353f00
|
2022-05-06 00:10:14
|
Lyn Nagara
|
feat(eventstream): Support producing to separate transactions topic (#34276)
| false
|
Support producing to separate transactions topic (#34276)
|
feat
|
diff --git a/src/sentry/eventstream/kafka/backend.py b/src/sentry/eventstream/kafka/backend.py
index 747de9f10b8d00..41642debce6c5b 100644
--- a/src/sentry/eventstream/kafka/backend.py
+++ b/src/sentry/eventstream/kafka/backend.py
@@ -31,6 +31,7 @@
class KafkaEventStream(SnubaProtocolEventStream):
def __init__(self, **options):
self.topic = settings.KAFKA_TOPICS[settings.KAFKA_EVENTS]["topic"]
+ self.transactions_topic = settings.KAFKA_TOPICS[settings.KAFKA_TRANSACTIONS]["topic"]
@cached_property
def producer(self):
@@ -105,10 +106,6 @@ def strip_none_values(value: Mapping[str, Optional[str]]) -> Mapping[str, str]:
),
}
- @staticmethod
- def _is_transaction_event(event) -> bool:
- return event.group_id is None
-
def insert(
self,
group,
@@ -150,6 +147,7 @@ def _send(
asynchronous: bool = True,
headers: Optional[Mapping[str, str]] = None,
skip_semantic_partitioning: bool = False,
+ is_transaction_event: bool = False,
):
if headers is None:
headers = {}
@@ -171,8 +169,10 @@ def _send(
assert isinstance(extra_data, tuple)
try:
+ topic = self.transactions_topic if is_transaction_event else self.topic
+
self.producer.produce(
- topic=self.topic,
+ topic=topic,
key=str(project_id).encode("utf-8") if not skip_semantic_partitioning else None,
value=json.dumps((self.EVENT_PROTOCOL_VERSION, _type) + extra_data),
on_delivery=self.delivery_callback,
diff --git a/src/sentry/eventstream/snuba.py b/src/sentry/eventstream/snuba.py
index 73e22845c93d12..a9ff5101844960 100644
--- a/src/sentry/eventstream/snuba.py
+++ b/src/sentry/eventstream/snuba.py
@@ -89,6 +89,10 @@ def _get_headers_for_insert(
) -> Mapping[str, str]:
return {"Received-Timestamp": str(received_timestamp)}
+ @staticmethod
+ def _is_transaction_event(event) -> bool:
+ return event.group_id is None
+
def insert(
self,
group,
@@ -132,6 +136,8 @@ def insert(
else False
)
+ is_transaction_event = self._is_transaction_event(event)
+
self._send(
project.id,
"insert",
@@ -159,6 +165,7 @@ def insert(
),
headers=headers,
skip_semantic_partitioning=skip_semantic_partitioning,
+ is_transaction_event=is_transaction_event,
)
def start_delete_groups(self, project_id, group_ids):
@@ -317,6 +324,7 @@ def _send(
asynchronous: bool = True,
headers: Optional[Mapping[str, str]] = None,
skip_semantic_partitioning: bool = False,
+ is_transaction_event: bool = False,
):
raise NotImplementedError
@@ -330,6 +338,7 @@ def _send(
asynchronous: bool = True,
headers: Optional[Mapping[str, str]] = None,
skip_semantic_partitioning: bool = False,
+ is_transaction_event: bool = False,
):
if headers is None:
headers = {}
@@ -337,7 +346,7 @@ def _send(
data = (self.EVENT_PROTOCOL_VERSION, _type) + extra_data
dataset = "events"
- if get_path(extra_data, 0, "data", "type") == "transaction":
+ if is_transaction_event:
dataset = "transactions"
try:
resp = snuba._snuba_pool.urlopen(
diff --git a/tests/snuba/eventstream/test_eventstream.py b/tests/snuba/eventstream/test_eventstream.py
index 13c7da58e773c8..7ec42aaf1cc797 100644
--- a/tests/snuba/eventstream/test_eventstream.py
+++ b/tests/snuba/eventstream/test_eventstream.py
@@ -52,7 +52,12 @@ def __produce_event(self, *insert_args, **insert_kwargs):
# insert what would have been the Kafka payload directly
# into Snuba, expect an HTTP 200 and for the event to now exist
snuba_eventstream = SnubaEventStream()
- snuba_eventstream._send(self.project.id, "insert", (payload1, payload2))
+ snuba_eventstream._send(
+ self.project.id,
+ "insert",
+ (payload1, payload2),
+ is_transaction_event=insert_kwargs["group"] is None,
+ )
@patch("sentry.eventstream.insert")
def test(self, mock_eventstream_insert):
|
3de8f1c1ee7e0ba2c957286d6b1cd78a350add1c
|
2020-04-23 20:38:06
|
Jan Michael Auer
|
feat(filters): Add an IE11 inbound data filter (#18434)
| false
|
Add an IE11 inbound data filter (#18434)
|
feat
|
diff --git a/src/sentry/message_filters.py b/src/sentry/message_filters.py
index bd42d2ceecfeec..b60b7e940b33c5 100644
--- a/src/sentry/message_filters.py
+++ b/src/sentry/message_filters.py
@@ -377,6 +377,7 @@ class _LegacyBrowserFilterSerializer(serializers.Serializer):
"ie_pre_9",
"ie9",
"ie10",
+ "ie11",
"opera_pre_15",
"android_pre_4",
"safari_pre_6",
@@ -474,6 +475,10 @@ def _filter_opera_mini_pre_8(browser):
return False
+def _filter_ie11(browser):
+ return _filter_ie_internal(browser, lambda major_ver: major_ver == 11)
+
+
def _filter_ie10(browser):
return _filter_ie_internal(browser, lambda major_ver: major_ver == 10)
@@ -507,6 +512,7 @@ def _filter_ie_internal(browser, compare_version):
"opera_mini_pre_8": _filter_opera_mini_pre_8,
"ie9": _filter_ie9,
"ie10": _filter_ie10,
+ "ie11": _filter_ie11,
"ie_pre_9": _filter_ie_pre_9,
}
diff --git a/src/sentry/static/sentry/app/views/settings/project/projectFilters/projectFiltersSettings.jsx b/src/sentry/static/sentry/app/views/settings/project/projectFilters/projectFiltersSettings.jsx
index 4d7ea3566f9c3e..a3e63083414a5a 100644
--- a/src/sentry/static/sentry/app/views/settings/project/projectFilters/projectFiltersSettings.jsx
+++ b/src/sentry/static/sentry/app/views/settings/project/projectFilters/projectFiltersSettings.jsx
@@ -39,6 +39,11 @@ const LEGACY_BROWSER_SUBFILTERS = {
helpText: 'Version 10',
title: 'Internet Explorer',
},
+ ie11: {
+ icon: 'internet-explorer',
+ helpText: 'Version 11',
+ title: 'Internet Explorer',
+ },
safari_pre_6: {
icon: 'safari',
helpText: 'Version 5 and lower',
diff --git a/tests/js/spec/views/projectFilters.spec.jsx b/tests/js/spec/views/projectFilters.spec.jsx
index fd3851dec35e86..0c896782be7159 100644
--- a/tests/js/spec/views/projectFilters.spec.jsx
+++ b/tests/js/spec/views/projectFilters.spec.jsx
@@ -132,7 +132,7 @@ describe('ProjectFilters', function() {
expect(Array.from(mock.mock.calls[0][1].data.subfilters)).toEqual([
'ie_pre_9',
'ie9',
- 'opera_pre_15',
+ 'safari_pre_6',
]);
// Toggle filter off
@@ -143,8 +143,8 @@ describe('ProjectFilters', function() {
expect(Array.from(mock.mock.calls[1][1].data.subfilters)).toEqual([
'ie_pre_9',
'ie9',
- 'opera_pre_15',
'safari_pre_6',
+ 'ie11',
]);
mock.mockReset();
@@ -160,8 +160,8 @@ describe('ProjectFilters', function() {
.simulate('click');
expect(Array.from(mock.mock.calls[1][1].data.subfilters)).toEqual([
- 'opera_pre_15',
'safari_pre_6',
+ 'ie11',
]);
});
@@ -178,6 +178,7 @@ describe('ProjectFilters', function() {
'ie_pre_9',
'ie9',
'ie10',
+ 'ie11',
'safari_pre_6',
'opera_pre_15',
'opera_mini_pre_8',
|
f45ad243c064ee0d9dbda38da6cb791602c93539
|
2024-04-01 22:16:35
|
Ryan Albrecht
|
feat(replay): Count additions & removals in the Replay Details > Dom chart (#67975)
| false
|
Count additions & removals in the Replay Details > Dom chart (#67975)
|
feat
|
diff --git a/static/app/utils/replays/countDomNodes.tsx b/static/app/utils/replays/countDomNodes.tsx
index ada5c24abc2f07..f219f504e0258c 100644
--- a/static/app/utils/replays/countDomNodes.tsx
+++ b/static/app/utils/replays/countDomNodes.tsx
@@ -2,8 +2,10 @@ import replayerStepper from 'sentry/utils/replays/replayerStepper';
import type {RecordingFrame} from 'sentry/utils/replays/types';
export type DomNodeChartDatapoint = {
+ added: number;
count: number;
endTimestampMs: number;
+ removed: number;
startTimestampMs: number;
timestampMs: number;
};
@@ -23,6 +25,8 @@ export default function countDomNodes({
const length = frames?.length ?? 0;
const frameStep = Math.max(Math.round(length * 0.007), 1);
+ let prevIds: number[] = [];
+
return replayerStepper<RecordingFrame, DomNodeChartDatapoint>({
frames,
rrwebEvents,
@@ -32,13 +36,19 @@ export default function countDomNodes({
return frameCount % frameStep === 0;
},
onVisitFrame: (frame, collection, replayer) => {
- const idCount = replayer.getMirror().getIds().length; // gets number of DOM nodes present
+ const ids = replayer.getMirror().getIds(); // gets list of DOM nodes present
+ const count = ids.length;
+ const added = ids.filter(id => !prevIds.includes(id)).length;
+ const removed = prevIds.filter(id => !ids.includes(id)).length;
collection.set(frame as RecordingFrame, {
- count: idCount,
+ count,
+ added,
+ removed,
timestampMs: frame.timestamp,
startTimestampMs: frame.timestamp,
endTimestampMs: frame.timestamp,
});
+ prevIds = ids;
},
});
}
diff --git a/static/app/views/replays/detail/memoryPanel/domNodesChart.tsx b/static/app/views/replays/detail/memoryPanel/domNodesChart.tsx
index e4c458bc19839c..0027b42f8574b3 100644
--- a/static/app/views/replays/detail/memoryPanel/domNodesChart.tsx
+++ b/static/app/views/replays/detail/memoryPanel/domNodesChart.tsx
@@ -1,7 +1,7 @@
-import {useMemo} from 'react';
+import {useMemo, useRef} from 'react';
import {useTheme} from '@emotion/react';
-import type {AreaChartProps} from 'sentry/components/charts/areaChart';
+import type {AreaChartProps, AreaChartSeries} from 'sentry/components/charts/areaChart';
import {AreaChart} from 'sentry/components/charts/areaChart';
import Grid from 'sentry/components/charts/components/grid';
import {computeChartTooltip} from 'sentry/components/charts/components/tooltip';
@@ -11,9 +11,9 @@ import type {useReplayContext} from 'sentry/components/replays/replayContext';
import {formatTime} from 'sentry/components/replays/utils';
import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
-import type {Series} from 'sentry/types/echarts';
import {getFormattedDate} from 'sentry/utils/dates';
import {axisLabelFormatter} from 'sentry/utils/discover/charts';
+import domId from 'sentry/utils/domId';
import type {DomNodeChartDatapoint} from 'sentry/utils/replays/countDomNodes';
import toArray from 'sentry/utils/toArray';
@@ -24,7 +24,6 @@ interface Props
> {
datapoints: DomNodeChartDatapoint[];
durationMs: number;
- startOffsetMs: number;
startTimestampMs: number;
}
@@ -35,101 +34,124 @@ export default function DomNodesChart({
datapoints,
setCurrentHoverTime,
setCurrentTime,
- startOffsetMs,
startTimestampMs,
}: Props) {
const theme = useTheme();
+ const idRef = useRef(domId('replay-dom-nodes-chart-'));
- const chartOptions: Omit<AreaChartProps, 'series'> = {
- autoHeightResize: true,
- height: 'auto',
- grid: Grid({
- top: '40px',
- left: space(1),
- right: space(1),
- }),
- tooltip: computeChartTooltip(
- {
- appendToBody: true,
- trigger: 'axis',
- renderMode: 'html',
- chartId: 'replay-dom-nodes-chart',
- formatter: values => {
- const firstValue = Array.isArray(values) ? values[0] : values;
- const seriesTooltips = toArray(values).map(
- value => `
+ const chartOptions: Omit<AreaChartProps, 'series'> = useMemo(
+ () => ({
+ autoHeightResize: true,
+ height: 'auto',
+ grid: Grid({
+ left: space(1),
+ right: space(1),
+ }),
+ tooltip: computeChartTooltip(
+ {
+ appendToBody: true,
+ trigger: 'axis',
+ renderMode: 'html',
+ chartId: idRef.current,
+ formatter: values => {
+ const firstValue = Array.isArray(values) ? values[0] : values;
+ const seriesTooltips = toArray(values).map(
+ value => `
<div>
<span className="tooltip-label">${value.marker}<strong>${value.seriesName}</strong></span>
${value.data[1]}
</div>
`
- );
+ );
- return `
+ return `
<div class="tooltip-series">${seriesTooltips.join('')}</div>
<div class="tooltip-footer">
- ${t('Date: %s', getFormattedDate(startOffsetMs + firstValue.axisValue, 'MMM D, YYYY hh:mm:ss A z', {local: false}))}
+ ${t('Date: %s', getFormattedDate(startTimestampMs + firstValue.axisValue, 'MMM D, YYYY hh:mm:ss A z', {local: false}))}
</div>
<div class="tooltip-footer" style="border: none;">
${t('Time within replay: %s', formatTime(firstValue.axisValue))}
</div>
<div class="tooltip-arrow"></div>
`;
+ },
},
+ theme
+ ),
+ xAxis: XAxis({
+ type: 'time',
+ axisLabel: {
+ formatter: (time: number) => formatTime(startTimestampMs + time, false),
+ },
+ theme,
+ }),
+ yAxis: YAxis({
+ type: 'value',
+ theme,
+ minInterval: 100,
+ maxInterval: 10_000,
+ axisLabel: {
+ formatter: (value: number) => axisLabelFormatter(value, 'number', true),
+ },
+ }),
+ onMouseOver: ({data}) => {
+ if (data[0]) {
+ setCurrentHoverTime(data[0]);
+ }
},
- theme
- ),
- xAxis: XAxis({
- type: 'time',
- axisLabel: {
- formatter: (time: number) => formatTime(time, false),
- },
- theme,
- }),
- yAxis: YAxis({
- type: 'value',
- name: t('DOM Nodes'),
- theme,
- nameTextStyle: {
- padding: [8, 8, 8, 48],
- fontSize: theme.fontSizeLarge,
- fontWeight: 600,
- lineHeight: 1.2,
- fontFamily: theme.text.family,
- color: theme.gray300,
+ onMouseOut: () => {
+ setCurrentHoverTime(undefined);
},
- minInterval: 100,
- maxInterval: Math.pow(1024, 4),
- axisLabel: {
- formatter: (value: number) => axisLabelFormatter(value, 'number', true),
+ onClick: ({data}) => {
+ if (data.value) {
+ setCurrentTime(data.value);
+ }
},
}),
- onMouseOver: ({data}) => {
- if (data[0]) {
- setCurrentHoverTime(data[0]);
- }
- },
- onMouseOut: () => {
- setCurrentHoverTime(undefined);
- },
- onClick: ({data}) => {
- if (data.value) {
- setCurrentTime(data.value);
- }
- },
- };
+ [setCurrentHoverTime, setCurrentTime, startTimestampMs, theme]
+ );
- const staticSeries: Series[] = useMemo(
+ const staticSeries = useMemo<AreaChartSeries[]>(
() => [
{
id: 'nodeCount',
- seriesName: t('Number of DOM nodes'),
+ seriesName: t('Total DOM nodes'),
data: datapoints.map(d => ({
value: d.count,
name: d.endTimestampMs - startTimestampMs,
})),
- stack: 'dom-nodes',
- lineStyle: {opacity: 0, width: 2},
+ stack: 'node-count',
+ lineStyle: {opacity: 1, width: 2},
+ },
+ {
+ id: 'addedCount',
+ seriesName: t('DOM Nodes added'),
+ data: datapoints.map(d => ({
+ value: d.added,
+ name: d.endTimestampMs - startTimestampMs,
+ })),
+ stack: 'added-count',
+ emphasis: {
+ focus: 'series',
+ },
+ color: theme.green300,
+ lineStyle: {opacity: 1, color: theme.green300, width: 2},
+ areaStyle: {opacity: 0, color: 'transparent'},
+ },
+ {
+ id: 'removedCount',
+ seriesName: t('DOM Nodes removed'),
+ data: datapoints.map(d => ({
+ value: d.removed,
+ name: d.endTimestampMs - startTimestampMs,
+ })),
+ stack: 'removed-count',
+ emphasis: {
+ focus: 'series',
+ },
+ color: theme.red300,
+ lineStyle: {opacity: 1, color: theme.red300, width: 2},
+ areaStyle: {opacity: 0, color: 'transparent'},
},
{
id: 'replayStart',
@@ -144,11 +166,11 @@ export default function DomNodesChart({
lineStyle: {opacity: 0, width: 0},
},
],
- [datapoints, durationMs, startTimestampMs]
+ [datapoints, durationMs, startTimestampMs, theme]
);
- const dynamicSeries = useMemo(
- (): Series[] => [
+ const dynamicSeries = useMemo<AreaChartSeries[]>(
+ () => [
{
id: 'hoverTime',
seriesName: t('Hover player time'),
@@ -180,5 +202,9 @@ export default function DomNodesChart({
[dynamicSeries, staticSeries]
);
- return <AreaChart series={series} {...chartOptions} />;
+ return (
+ <div id={idRef.current}>
+ <AreaChart series={series} {...chartOptions} />
+ </div>
+ );
}
diff --git a/static/app/views/replays/detail/memoryPanel/index.tsx b/static/app/views/replays/detail/memoryPanel/index.tsx
index 02ec4401a62fb2..022e843d4187cc 100644
--- a/static/app/views/replays/detail/memoryPanel/index.tsx
+++ b/static/app/views/replays/detail/memoryPanel/index.tsx
@@ -1,4 +1,4 @@
-import {useMemo} from 'react';
+import {Fragment, useMemo} from 'react';
import styled from '@emotion/styled';
import EmptyMessage from 'sentry/components/emptyMessage';
@@ -55,31 +55,36 @@ export default function MemoryPanel() {
)}
/>
) : (
- <MemoryChart
- currentHoverTime={currentHoverTime}
- currentTime={currentTime}
- durationMs={replay.getDurationMs()}
- memoryFrames={memoryFrames}
- setCurrentHoverTime={setCurrentHoverTime}
- setCurrentTime={setCurrentTime}
- startOffsetMs={replay.getStartOffsetMs()}
- />
+ <Fragment>
+ <ChartTitle>{t('Heap Size')}</ChartTitle>
+ <MemoryChart
+ currentHoverTime={currentHoverTime}
+ currentTime={currentTime}
+ durationMs={replay.getDurationMs()}
+ memoryFrames={memoryFrames}
+ setCurrentHoverTime={setCurrentHoverTime}
+ setCurrentTime={setCurrentTime}
+ startTimestampMs={replay.getStartTimestampMs()}
+ />
+ </Fragment>
);
const domNodesChart =
!replay || isFetching ? (
<Placeholder height="100%" />
) : (
- <DomNodesChart
- currentHoverTime={currentHoverTime}
- currentTime={currentTime}
- durationMs={replay.getDurationMs()}
- datapoints={domNodeData}
- setCurrentHoverTime={setCurrentHoverTime}
- setCurrentTime={setCurrentTime}
- startOffsetMs={replay.getStartOffsetMs()}
- startTimestampMs={replay.getStartTimestampMs()}
- />
+ <Fragment>
+ <ChartTitle>{t('DOM Nodes')}</ChartTitle>
+ <DomNodesChart
+ currentHoverTime={currentHoverTime}
+ currentTime={currentTime}
+ durationMs={replay.getDurationMs()}
+ datapoints={domNodeData}
+ setCurrentHoverTime={setCurrentHoverTime}
+ setCurrentTime={setCurrentTime}
+ startTimestampMs={replay.getStartTimestampMs()}
+ />
+ </Fragment>
);
return (
@@ -105,7 +110,17 @@ const ChartWrapper = styled('div')`
padding: ${space(1)};
overflow: hidden;
display: flex;
+ flex-direction: column;
& > * {
flex-grow: 1;
}
`;
+
+const ChartTitle = styled('h5')`
+ font-size: ${p => p.theme.fontSizeLarge};
+ font-weight: ${p => p.theme.text.cardTitle.fontWeight};
+ line-height: ${p => p.theme.text.cardTitle.lineHeight};
+ color: ${p => p.theme.subText};
+ flex: 0 1 auto;
+ margin: 0;
+`;
diff --git a/static/app/views/replays/detail/memoryPanel/memoryChart.tsx b/static/app/views/replays/detail/memoryPanel/memoryChart.tsx
index f662283d1c4e7d..ffa5ec3c293ed0 100644
--- a/static/app/views/replays/detail/memoryPanel/memoryChart.tsx
+++ b/static/app/views/replays/detail/memoryPanel/memoryChart.tsx
@@ -1,7 +1,7 @@
-import {useMemo} from 'react';
+import {useMemo, useRef} from 'react';
import {useTheme} from '@emotion/react';
-import type {AreaChartProps} from 'sentry/components/charts/areaChart';
+import type {AreaChartProps, AreaChartSeries} from 'sentry/components/charts/areaChart';
import {AreaChart} from 'sentry/components/charts/areaChart';
import Grid from 'sentry/components/charts/components/grid';
import {computeChartTooltip} from 'sentry/components/charts/components/tooltip';
@@ -11,9 +11,9 @@ import type {useReplayContext} from 'sentry/components/replays/replayContext';
import {formatTime} from 'sentry/components/replays/utils';
import {t} from 'sentry/locale';
import {space} from 'sentry/styles/space';
-import type {Series} from 'sentry/types/echarts';
import {formatBytesBase2} from 'sentry/utils';
import {getFormattedDate} from 'sentry/utils/dates';
+import domId from 'sentry/utils/domId';
import type {MemoryFrame} from 'sentry/utils/replays/types';
import toArray from 'sentry/utils/toArray';
@@ -24,7 +24,7 @@ interface Props
> {
durationMs: number;
memoryFrames: MemoryFrame[];
- startOffsetMs: number;
+ startTimestampMs: number;
}
export default function MemoryChart({
@@ -34,17 +34,16 @@ export default function MemoryChart({
memoryFrames,
setCurrentHoverTime,
setCurrentTime,
- startOffsetMs,
+ startTimestampMs,
}: Props) {
const theme = useTheme();
+ const idRef = useRef(domId('replay-memory-chart-'));
const chartOptions: Omit<AreaChartProps, 'series'> = useMemo(
() => ({
autoHeightResize: true,
height: 'auto',
grid: Grid({
- // makes space for the title
- top: '40px',
left: space(1),
right: space(1),
}),
@@ -53,7 +52,7 @@ export default function MemoryChart({
appendToBody: true,
trigger: 'axis',
renderMode: 'html',
- chartId: 'replay-memory-chart',
+ chartId: idRef.current,
formatter: values => {
const firstValue = Array.isArray(values) ? values[0] : values;
const seriesTooltips = toArray(values).map(
@@ -67,7 +66,7 @@ export default function MemoryChart({
return `
<div class="tooltip-series">${seriesTooltips.join('')}</div>
<div class="tooltip-footer">
- ${t('Date: %s', getFormattedDate(startOffsetMs + firstValue.axisValue, 'MMM D, YYYY hh:mm:ss A z', {local: false}))}
+ ${t('Date: %s', getFormattedDate(startTimestampMs + firstValue.axisValue, 'MMM D, YYYY hh:mm:ss A z', {local: false}))}
</div>
<div class="tooltip-footer" style="border: none;">
${t('Time within replay: %s', formatTime(firstValue.axisValue))}
@@ -81,28 +80,17 @@ export default function MemoryChart({
xAxis: XAxis({
type: 'time',
axisLabel: {
- formatter: (time: number) => formatTime(time, false),
+ formatter: (time: number) => formatTime(startTimestampMs + time, false),
},
theme,
}),
yAxis: YAxis({
type: 'value',
- name: t('Heap Size'),
theme,
- nameTextStyle: {
- padding: [8, 8, 8, -25],
- fontSize: theme.fontSizeLarge,
- fontWeight: 600,
- lineHeight: 1.2,
- fontFamily: theme.text.family,
- color: theme.gray300,
- },
- // input is in bytes, minInterval is a megabyte
- minInterval: 1024 * 1024,
- // maxInterval is a terabyte
- maxInterval: Math.pow(1024, 4),
- // format the axis labels to be whole number values
+ minInterval: 1024 * 1024, // input is in bytes, minInterval is a megabyte
+ maxInterval: Math.pow(1024, 4), // maxInterval is a terabyte
axisLabel: {
+ // format the axis labels to be whole number values
formatter: value => formatBytesBase2(value, 0),
},
}),
@@ -120,10 +108,10 @@ export default function MemoryChart({
}
},
}),
- [setCurrentHoverTime, setCurrentTime, startOffsetMs, theme]
+ [setCurrentHoverTime, setCurrentTime, startTimestampMs, theme]
);
- const staticSeries: Series[] = useMemo(
+ const staticSeries = useMemo<AreaChartSeries[]>(
() => [
{
id: 'usedMemory',
@@ -151,8 +139,8 @@ export default function MemoryChart({
[durationMs, memoryFrames]
);
- const dynamicSeries = useMemo(
- (): Series[] => [
+ const dynamicSeries = useMemo<AreaChartSeries[]>(
+ () => [
{
id: 'currentTime',
seriesName: t('Current player time'),
@@ -185,8 +173,8 @@ export default function MemoryChart({
);
return (
- <div id="replay-memory-chart">
- <AreaChart autoHeightResize height="auto" series={series} {...chartOptions} />
+ <div id={idRef.current}>
+ <AreaChart series={series} {...chartOptions} />
</div>
);
}
|
e8cb8e9afee3f4bc290b56dd3c757119d22ee8d9
|
2022-03-09 01:09:22
|
Zhixing Zhang
|
fix(report): Use a different category for sendgrid (#32430)
| false
|
Use a different category for sendgrid (#32430)
|
fix
|
diff --git a/src/sentry/tasks/reports.py b/src/sentry/tasks/reports.py
index e51de07c86dce5..778949a2ca34c2 100644
--- a/src/sentry/tasks/reports.py
+++ b/src/sentry/tasks/reports.py
@@ -852,11 +852,11 @@ def build_message(timestamp, duration, organization, user, reports):
start, stop = interval = _to_interval(timestamp, duration)
duration_spec = durations[duration]
- html_template = None
+ html_template = "sentry/emails/reports/body.html"
+ smtp_category = "organization_report_email"
if features.has("organizations:new-weekly-report", organization, actor=user):
html_template = "sentry/emails/reports/new.html"
- else:
- html_template = "sentry/emails/reports/body.html"
+ smtp_category = "organization_report_email_new"
message = MessageBuilder(
subject="{} Report for {}: {} - {}".format(
@@ -876,7 +876,7 @@ def build_message(timestamp, duration, organization, user, reports):
"report": to_context(organization, interval, reports),
"user": user,
},
- headers={"X-SMTPAPI": json.dumps({"category": "organization_report_email"})},
+ headers={"X-SMTPAPI": json.dumps({"category": smtp_category})},
)
message.add_users((user.id,))
|
25b08ee2861a888140ea6d060e76bc47c78bfbc3
|
2024-03-19 01:02:35
|
Jonas
|
fix(trace): fix button position (#67172)
| false
|
fix button position (#67172)
|
fix
|
diff --git a/static/app/views/performance/newTraceDetails/trace.tsx b/static/app/views/performance/newTraceDetails/trace.tsx
index 600a5883ed6596..272d22d52b1a1d 100644
--- a/static/app/views/performance/newTraceDetails/trace.tsx
+++ b/static/app/views/performance/newTraceDetails/trace.tsx
@@ -2090,6 +2090,9 @@ const TraceStylingWrapper = styled('div')`
color: ${p => p.theme.white};
background-color: ${p => p.theme.blue300};
}
+ svg {
+ fill: ${p => p.theme.white};
+ }
}
}
}
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/details/span.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/details/span.tsx
index 9ac085295d230a..50be8c88f51609 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/details/span.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/details/span.tsx
@@ -49,13 +49,15 @@ export function SpanNodeDetails({
</TraceDrawerComponents.TitleOp>
</div>
</TraceDrawerComponents.Title>
- <Button size="xs" onClick={_e => scrollToNode(node)}>
- {t('Show in view')}
- </Button>
- <TraceDrawerComponents.EventDetailsLink
- eventId={node.value.event.eventID}
- projectSlug={node.metadata.project_slug}
- />
+ <TraceDrawerComponents.Actions>
+ <Button size="xs" onClick={_e => scrollToNode(node)}>
+ {t('Show in view')}
+ </Button>
+ <TraceDrawerComponents.EventDetailsLink
+ eventId={node.value.event.eventID}
+ projectSlug={node.metadata.project_slug}
+ />
+ </TraceDrawerComponents.Actions>
</TraceDrawerComponents.HeaderContainer>
{event.projectSlug && (
<ProfilesProvider
diff --git a/static/app/views/performance/newTraceDetails/traceDrawer/traceDrawer.tsx b/static/app/views/performance/newTraceDetails/traceDrawer/traceDrawer.tsx
index 85a7f4247a5037..7df9bed1b19327 100644
--- a/static/app/views/performance/newTraceDetails/traceDrawer/traceDrawer.tsx
+++ b/static/app/views/performance/newTraceDetails/traceDrawer/traceDrawer.tsx
@@ -278,6 +278,8 @@ const TabsContainer = styled('ul')<{hasIndicators: boolean}>`
const TabLayoutControlsContainer = styled('ul')`
list-style-type: none;
padding-left: 0;
+ margin-left: auto;
+ margin-right: ${space(1.5)};
button {
padding: ${space(0.5)};
|
a3e013d368c650ed491e78761283e0204cdf7fff
|
2021-07-20 04:57:43
|
Scott Cooper
|
test(ui): Split create alert add/remove filters (#27563)
| false
|
Split create alert add/remove filters (#27563)
|
test
|
diff --git a/tests/js/spec/views/alerts/create.spec.jsx b/tests/js/spec/views/alerts/create.spec.jsx
index 20ada03f9558fa..52fce6bd1bef2a 100644
--- a/tests/js/spec/views/alerts/create.spec.jsx
+++ b/tests/js/spec/views/alerts/create.spec.jsx
@@ -157,15 +157,71 @@ describe('ProjectAlertsCreate', function () {
expect(getByDisplayValue('30')).toBeInTheDocument();
});
- it('updates values and saves', async function () {
+ it('can remove filters, conditions and actions', async function () {
const {
- wrapper: {
- getAllByLabelText,
- getAllByText,
- getByLabelText,
- getByPlaceholderText,
- getByText,
+ wrapper: {getByLabelText, getByPlaceholderText, getByText},
+ } = createWrapper({
+ organization: {
+ features: ['alert-filters'],
},
+ });
+ const mock = MockApiClient.addMockResponse({
+ url: '/projects/org-slug/project-slug/rules/',
+ method: 'POST',
+ body: TestStubs.ProjectAlertRule(),
+ });
+
+ await waitFor(() => {
+ expect(memberActionCreators.fetchOrgMembers).toHaveBeenCalled();
+ });
+
+ // Change name of alert rule
+ fireEvent.change(getByPlaceholderText('My Rule Name'), {
+ target: {value: 'My Rule Name'},
+ });
+
+ // Add a condition and remove it
+ await selectEvent.select(getByText('Add optional condition...'), [
+ 'A new issue is created',
+ ]);
+ fireEvent.click(getByLabelText('Delete Node'));
+
+ // Add a filter and remove it
+ await selectEvent.select(getByText('Add optional filter...'), [
+ 'The issue is {comparison_type} than {value} {time}',
+ ]);
+ fireEvent.click(getByLabelText('Delete Node'));
+
+ // Add an action and remove it
+ await selectEvent.select(getByText('Add action...'), [
+ 'Send a notification (for all legacy integrations)',
+ ]);
+ fireEvent.click(getByLabelText('Delete Node'));
+
+ fireEvent.click(getByText('Save Rule'));
+
+ await waitFor(() => {
+ expect(mock).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ data: {
+ actionMatch: 'all',
+ actions: [],
+ conditions: [],
+ filterMatch: 'all',
+ filters: [],
+ frequency: 30,
+ name: 'My Rule Name',
+ owner: null,
+ },
+ })
+ );
+ });
+ });
+
+ it('updates values and saves', async function () {
+ const {
+ wrapper: {getAllByText, getByPlaceholderText, getByText},
router,
} = createWrapper({
organization: {
@@ -184,6 +240,7 @@ describe('ProjectAlertsCreate', function () {
// Change target environment
await selectEvent.select(getByText('All Environments'), ['production']);
+
// Change actionMatch and filterMatch dropdown
await selectEvent.select(getAllByText('all')[0], ['any']);
await selectEvent.select(getAllByText('all')[0], ['any']);
@@ -193,12 +250,6 @@ describe('ProjectAlertsCreate', function () {
target: {value: 'My Rule Name'},
});
- // Add a condition and remove it
- await selectEvent.select(getByText('Add optional condition...'), [
- 'A new issue is created',
- ]);
- fireEvent.click(getByLabelText('Delete Node'));
-
// Add another condition
await selectEvent.select(getByText('Add optional condition...'), [
"An event's tags match {key} {match} {value}",
@@ -212,12 +263,6 @@ describe('ProjectAlertsCreate', function () {
});
await selectEvent.select(getByText('equals'), ['does not equal']);
- // Add a filter and remove it
- await selectEvent.select(getByText('Add optional filter...'), [
- 'The issue is {comparison_type} than {value} {time}',
- ]);
- fireEvent.click(getAllByLabelText('Delete Node')[1]);
-
// Add a new filter
await selectEvent.select(getByText('Add optional filter...'), [
'The issue is {comparison_type} than {value} {time}',
@@ -226,12 +271,6 @@ describe('ProjectAlertsCreate', function () {
target: {value: '12'},
});
- // Add an action and remove it
- await selectEvent.select(getByText('Add action...'), [
- 'Send a notification (for all legacy integrations)',
- ]);
- fireEvent.click(getAllByLabelText('Delete Node')[2]);
-
// Add a new action
await selectEvent.select(getByText('Add action...'), [
'Send a notification via {service}',
|
66a52784b8f3a402feee5f1f11f688bdada36c03
|
2024-05-16 00:33:07
|
George Gritsouk
|
fix(insights): Remove stray line of code (#70943)
| false
|
Remove stray line of code (#70943)
|
fix
|
diff --git a/static/app/views/performance/http/data/useSpanSamples.tsx b/static/app/views/performance/http/data/useSpanSamples.tsx
index 49565ec5517a6b..ab2fc7394066e1 100644
--- a/static/app/views/performance/http/data/useSpanSamples.tsx
+++ b/static/app/views/performance/http/data/useSpanSamples.tsx
@@ -63,7 +63,6 @@ export const useSpanSamples = <Fields extends IndexedProperty[]>(
// This type is a little awkward but it explicitly states that the response could be empty. This doesn't enable unchecked access errors, but it at least indicates that it's possible that there's no data
// eslint-disable-next-line @typescript-eslint/ban-types
| [];
- meta: 'hello';
}>(
[
`/api/0/organizations/${organization.slug}/spans-samples/`,
|
50f3446cf27905dc9475941fab1a62182a888148
|
2020-08-18 22:20:39
|
David Wang
|
fix(alerts): Show create alert from discover/performance conditionally #20256
| false
|
Show create alert from discover/performance conditionally #20256
|
fix
|
diff --git a/src/sentry/static/sentry/app/views/eventsV2/savedQuery/index.tsx b/src/sentry/static/sentry/app/views/eventsV2/savedQuery/index.tsx
index f484cc79d37dc9..f96ddbddbeb674 100644
--- a/src/sentry/static/sentry/app/views/eventsV2/savedQuery/index.tsx
+++ b/src/sentry/static/sentry/app/views/eventsV2/savedQuery/index.tsx
@@ -10,6 +10,7 @@ import withApi from 'app/utils/withApi';
import Button from 'app/components/button';
import DropdownButton from 'app/components/dropdownButton';
import DropdownControl from 'app/components/dropdownControl';
+import Feature from 'app/components/acl/feature';
import Input from 'app/components/forms/input';
import space from 'app/styles/space';
import {IconBookmark, IconDelete} from 'app/icons';
@@ -323,9 +324,12 @@ class SavedQueryButtonGroup extends React.PureComponent<Props, State> {
}
render() {
+ const {organization} = this.props;
return (
<ButtonGroup>
- {this.renderButtonCreateAlert()}
+ <Feature organization={organization} features={['incidents']}>
+ {({hasFeature}) => hasFeature && this.renderButtonCreateAlert()}
+ </Feature>
{this.renderButtonDelete()}
{this.renderButtonSaveAs()}
{this.renderButtonUpdate()}
diff --git a/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx b/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
index a3290a553bc6c1..2c757bbbed22ad 100644
--- a/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
+++ b/src/sentry/static/sentry/app/views/performance/transactionSummary/content.tsx
@@ -9,6 +9,7 @@ import {getParams} from 'app/components/organizations/globalSelectionHeader/getP
import space from 'app/styles/space';
import {generateQueryWithTag} from 'app/utils';
import EventView from 'app/utils/discover/eventView';
+import Feature from 'app/components/acl/feature';
import * as Layout from 'app/components/layouts/thirds';
import Tags from 'app/views/eventsV2/tags';
import SearchBar from 'app/views/events/searchBar';
@@ -142,7 +143,9 @@ class SummaryContent extends React.Component<Props, State> {
</Layout.HeaderContent>
<Layout.HeaderActions>
<ButtonBar gap={1}>
- {this.renderCreateAlertButton()}
+ <Feature organization={organization} features={['incidents']}>
+ {({hasFeature}) => hasFeature && this.renderCreateAlertButton()}
+ </Feature>
{this.renderKeyTransactionButton()}
</ButtonBar>
</Layout.HeaderActions>
diff --git a/tests/js/spec/views/eventsV2/savedQuery/index.spec.jsx b/tests/js/spec/views/eventsV2/savedQuery/index.spec.jsx
index e7ef793c6d42d5..babc456489e87f 100644
--- a/tests/js/spec/views/eventsV2/savedQuery/index.spec.jsx
+++ b/tests/js/spec/views/eventsV2/savedQuery/index.spec.jsx
@@ -302,10 +302,14 @@ describe('EventsV2 > SaveQueryButtonGroup', function() {
});
});
describe('create alert from discover', () => {
- it('renders create alert button', () => {
+ it('renders create alert button when metrics alerts is enabled', () => {
+ const metricAlertOrg = {
+ ...organization,
+ features: ['incidents'],
+ };
const wrapper = generateWrappedComponent(
location,
- organization,
+ metricAlertOrg,
errorsViewModified,
savedQuery
);
@@ -313,5 +317,16 @@ describe('EventsV2 > SaveQueryButtonGroup', function() {
expect(buttonCreateAlert.exists()).toBe(true);
});
+ it('does not render create alert button without metric alerts', () => {
+ const wrapper = generateWrappedComponent(
+ location,
+ organization,
+ errorsViewModified,
+ savedQuery
+ );
+ const buttonCreateAlert = wrapper.find(SELECTOR_BUTTON_CREATE_ALERT);
+
+ expect(buttonCreateAlert.exists()).toBe(false);
+ });
});
});
diff --git a/tests/js/spec/views/performance/transactionSummary.spec.jsx b/tests/js/spec/views/performance/transactionSummary.spec.jsx
index b955b91a99fed8..81320dbf62c0bf 100644
--- a/tests/js/spec/views/performance/transactionSummary.spec.jsx
+++ b/tests/js/spec/views/performance/transactionSummary.spec.jsx
@@ -156,6 +156,26 @@ describe('Performance > TransactionSummary', function() {
// Ensure transaction filter button exists
expect(wrapper.find('[data-test-id="filter-transactions"]')).toHaveLength(1);
+
+ // Ensure create alert from discover is hidden without metric alert
+ expect(wrapper.find('CreateAlertButton')).toHaveLength(0);
+ });
+
+ it('renders feature flagged UI elements', async function() {
+ const initialData = initializeData();
+ initialData.organization.features.push('incidents');
+ const wrapper = mountWithTheme(
+ <TransactionSummary
+ organization={initialData.organization}
+ location={initialData.router.location}
+ />,
+ initialData.routerContext
+ );
+ await tick();
+ wrapper.update();
+
+ // Ensure create alert from discover is shown with metric alerts
+ expect(wrapper.find('CreateAlertButton')).toHaveLength(1);
});
it('triggers a navigation on search', async function() {
|
718203493b4fd3bfd140ea84a9479807949de1e8
|
2024-11-18 21:40:09
|
Leander Rodrigues
|
fix(project-details): Correct some types, don't crash on alert render fail (#80466)
| false
|
Correct some types, don't crash on alert render fail (#80466)
|
fix
|
diff --git a/static/app/components/globalEventProcessingAlert.tsx b/static/app/components/globalEventProcessingAlert.tsx
index 3565284f6ed921..f3e569a5c96de7 100644
--- a/static/app/components/globalEventProcessingAlert.tsx
+++ b/static/app/components/globalEventProcessingAlert.tsx
@@ -15,7 +15,7 @@ type Props = {
// This alert makes the user aware that one or more projects have been selected for the Low Priority Queue
function GlobalEventProcessingAlert({className, projects}: Props) {
const projectsInTheLowPriorityQueue = projects.filter(
- project => project.eventProcessing.symbolicationDegraded
+ project => project?.eventProcessing?.symbolicationDegraded
);
if (!projectsInTheLowPriorityQueue.length) {
diff --git a/static/app/types/project.tsx b/static/app/types/project.tsx
index d5bd5dcf76c278..0381bb57ddfb58 100644
--- a/static/app/types/project.tsx
+++ b/static/app/types/project.tsx
@@ -20,9 +20,6 @@ export type Project = {
digestsMinDelay: number;
dynamicSamplingBiases: DynamicSamplingBias[] | null;
environments: string[];
- eventProcessing: {
- symbolicationDegraded: boolean;
- };
features: string[];
firstEvent: string | null;
firstTransactionEvent: boolean;
@@ -67,6 +64,9 @@ export type Project = {
verifySSL: boolean;
builtinSymbolSources?: string[];
defaultEnvironment?: string;
+ eventProcessing?: {
+ symbolicationDegraded?: boolean;
+ };
hasUserReports?: boolean;
highlightContext?: Record<string, string[]>;
highlightPreset?: {
diff --git a/static/app/views/projectDetail/projectDetail.tsx b/static/app/views/projectDetail/projectDetail.tsx
index 996f5869a0ecb8..ef09c0800936de 100644
--- a/static/app/views/projectDetail/projectDetail.tsx
+++ b/static/app/views/projectDetail/projectDetail.tsx
@@ -10,6 +10,7 @@ import {Breadcrumbs} from 'sentry/components/breadcrumbs';
import {LinkButton} from 'sentry/components/button';
import ButtonBar from 'sentry/components/buttonBar';
import CreateAlertButton from 'sentry/components/createAlertButton';
+import ErrorBoundary from 'sentry/components/errorBoundary';
import FeedbackWidgetButton from 'sentry/components/feedback/widget/feedbackWidgetButton';
import GlobalEventProcessingAlert from 'sentry/components/globalEventProcessingAlert';
import IdBadge from 'sentry/components/idBadge';
@@ -206,7 +207,9 @@ export default function ProjectDetail({router, location, organization}: Props) {
</Layout.Header>
<Layout.Body noRowGap>
- {project && <StyledGlobalEventProcessingAlert projects={[project]} />}
+ <ErrorBoundary customComponent={null}>
+ {project && <StyledGlobalEventProcessingAlert projects={[project]} />}
+ </ErrorBoundary>
<Layout.Main>
<ProjectFiltersWrapper>
<ProjectFilters
|
44a70435909a8cb1ed6fbafc7875249cf388ef7b
|
2021-06-26 00:33:43
|
Richard Ma
|
fix(org-stats): NoProjects -> NoProjects("No projects available") (#26884)
| false
|
NoProjects -> NoProjects("No projects available") (#26884)
|
fix
|
diff --git a/src/sentry/api/endpoints/organization_stats_v2.py b/src/sentry/api/endpoints/organization_stats_v2.py
index 5925e4a9b8b99d..eb4a8557688bb4 100644
--- a/src/sentry/api/endpoints/organization_stats_v2.py
+++ b/src/sentry/api/endpoints/organization_stats_v2.py
@@ -46,7 +46,7 @@ def _get_projects_for_orgstats_query(self, request, organization):
else:
projects = self.get_projects(request, organization, project_ids=req_proj_ids)
if not projects:
- raise NoProjects
+ raise NoProjects("No projects available")
return [p.id for p in projects]
def _is_org_total_query(self, request, project_ids):
diff --git a/tests/snuba/api/endpoints/test_organization_stats_v2.py b/tests/snuba/api/endpoints/test_organization_stats_v2.py
index aa7d76fa419c5f..6cd257bad76e98 100644
--- a/tests/snuba/api/endpoints/test_organization_stats_v2.py
+++ b/tests/snuba/api/endpoints/test_organization_stats_v2.py
@@ -23,6 +23,7 @@ def setUp(self):
self.org.save()
self.org2 = self.create_organization()
+ self.org3 = self.create_organization()
self.project = self.create_project(
name="bar", teams=[self.create_team(organization=self.org, members=[self.user])]
@@ -34,6 +35,7 @@ def setUp(self):
self.user2 = self.create_user(is_superuser=False)
self.create_member(user=self.user2, organization=self.organization, role="member", teams=[])
+ self.create_member(user=self.user2, organization=self.org3, role="member", teams=[])
self.project4 = self.create_project(
name="users2sproj",
teams=[self.create_team(organization=self.org, members=[self.user2])],
@@ -107,6 +109,24 @@ def test_inaccessible_project(self):
"detail": "You do not have permission to perform this action."
}
+ def test_no_projects_available(self):
+ response = self.do_request(
+ {
+ "groupBy": ["project"],
+ "statsPeriod": "1d",
+ "interval": "1d",
+ "field": ["sum(quantity)"],
+ "category": ["error", "transaction"],
+ },
+ user=self.user2,
+ org=self.org3,
+ )
+
+ assert response.status_code == 400, response.content
+ assert result_sorted(response.data) == {
+ "detail": "No projects available",
+ }
+
def test_unknown_field(self):
response = self.do_request(
{
|
0c8111513f461da88aae8f6c5581b91f058396f4
|
2024-07-25 03:34:58
|
Ryan Albrecht
|
feat(toolbar): Iterate on feature-flags panel styles (#74910)
| false
|
Iterate on feature-flags panel styles (#74910)
|
feat
|
diff --git a/static/app/components/devtoolbar/components/featureFlags/featureFlagsPanel.tsx b/static/app/components/devtoolbar/components/featureFlags/featureFlagsPanel.tsx
index 35ea1e1d753d23..4d2884d28689b8 100644
--- a/static/app/components/devtoolbar/components/featureFlags/featureFlagsPanel.tsx
+++ b/static/app/components/devtoolbar/components/featureFlags/featureFlagsPanel.tsx
@@ -1,10 +1,8 @@
import {useRef, useState} from 'react';
import useEnabledFeatureFlags from 'sentry/components/devtoolbar/components/featureFlags/useEnabledFeatureFlags';
-import {
- infiniteListScrollableWindowCss,
- panelScrollableCss,
-} from 'sentry/components/devtoolbar/styles/infiniteList';
+import {inlineLinkCss} from 'sentry/components/devtoolbar/styles/link';
+import EmptyStateWarning from 'sentry/components/emptyStateWarning';
import Input from 'sentry/components/input';
import ExternalLink from 'sentry/components/links/externalLink';
import {PanelTable} from 'sentry/components/panels/panelTable';
@@ -12,7 +10,6 @@ import {Cell} from 'sentry/components/replays/virtualizedGrid/bodyCell';
import useConfiguration from '../../hooks/useConfiguration';
import {panelInsetContentCss, panelSectionCss} from '../../styles/panel';
-import {resetFlexColumnCss} from '../../styles/reset';
import {smallCss} from '../../styles/typography';
import PanelLayout from '../panelLayout';
@@ -22,30 +19,45 @@ export default function FeatureFlagsPanel() {
const [searchTerm, setSearchTerm] = useState('');
const searchInput = useRef<HTMLInputElement>(null);
+ const filteredItems = featureFlags
+ ?.filter(s => s.toLowerCase().includes(searchTerm))
+ .sort();
+
return (
<PanelLayout title="Feature Flags">
<div css={[smallCss, panelSectionCss, panelInsetContentCss]}>
- <Input
- ref={searchInput}
- size="sm"
- placeholder="Search flags"
- onChange={e => setSearchTerm(e.target.value.toLowerCase())}
- />
+ <span>Flags enabled for {organizationSlug}</span>
</div>
-
<PanelTable
- headers={[<span key="Flags">Flags enabled for {organizationSlug}</span>]}
- css={[resetFlexColumnCss, infiniteListScrollableWindowCss, panelScrollableCss]}
+ headers={[
+ <div key="column">
+ <Input
+ ref={searchInput}
+ size="sm"
+ placeholder="Search flags"
+ onChange={e => setSearchTerm(e.target.value.toLowerCase())}
+ />
+ </div>,
+ ]}
+ stickyHeaders
+ css={[
+ {
+ border: 'none',
+ padding: 0,
+ '&>:first-child': {
+ minHeight: 'unset',
+ padding: 'var(--space50) var(--space150)',
+ },
+ },
+ ]}
>
- {featureFlags
- ?.filter(s => s.toLowerCase().includes(searchTerm))
- .sort()
- .map(flag => {
+ {filteredItems?.length ? (
+ filteredItems.map(flag => {
return (
- <Cell key={flag} style={{alignItems: 'flex-start'}}>
+ <Cell key={flag} css={[panelInsetContentCss, {alignItems: 'flex-start'}]}>
{featureFlagTemplateUrl?.(flag) ? (
<ExternalLink
- style={{textDecoration: 'inherit', color: 'inherit'}}
+ css={[smallCss, inlineLinkCss]}
href={featureFlagTemplateUrl(flag)}
onClick={() => {
trackAnalytics?.({
@@ -61,7 +73,10 @@ export default function FeatureFlagsPanel() {
)}
</Cell>
);
- })}
+ })
+ ) : (
+ <EmptyStateWarning small>No items to show</EmptyStateWarning>
+ )}
</PanelTable>
</PanelLayout>
);
diff --git a/static/app/components/devtoolbar/styles/panel.ts b/static/app/components/devtoolbar/styles/panel.ts
index e0a1269e84b74e..8875b7ebc6db0d 100644
--- a/static/app/components/devtoolbar/styles/panel.ts
+++ b/static/app/components/devtoolbar/styles/panel.ts
@@ -35,5 +35,5 @@ export const panelSectionCss = css`
`;
export const panelInsetContentCss = css`
- padding-inline: var(--space100);
+ padding-inline: var(--space150);
`;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.