content.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. import {Fragment, useMemo} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location} from 'history';
  5. import omit from 'lodash/omit';
  6. import MarkArea from 'sentry/components/charts/components/markArea';
  7. import MarkLine from 'sentry/components/charts/components/markLine';
  8. import {LineChartSeries} from 'sentry/components/charts/lineChart';
  9. import DatePageFilter from 'sentry/components/datePageFilter';
  10. import EnvironmentPageFilter from 'sentry/components/environmentPageFilter';
  11. import SearchBar from 'sentry/components/events/searchBar';
  12. import * as Layout from 'sentry/components/layouts/thirds';
  13. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  14. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import {Organization} from 'sentry/types';
  18. import {defined} from 'sentry/utils';
  19. import EventView from 'sentry/utils/discover/eventView';
  20. import AnomaliesQuery, {
  21. AnomalyInfo,
  22. AnomalyPayload,
  23. ChildrenProps,
  24. } from 'sentry/utils/performance/anomalies/anomaliesQuery';
  25. import {decodeScalar} from 'sentry/utils/queryString';
  26. import theme from 'sentry/utils/theme';
  27. import {GenericPerformanceWidget} from '../../landing/widgets/components/performanceWidget';
  28. import {WidgetEmptyStateWarning} from '../../landing/widgets/components/selectableList';
  29. import {QueryDefinition, WidgetDataResult} from '../../landing/widgets/types';
  30. import {
  31. PerformanceWidgetSetting,
  32. WIDGET_DEFINITIONS,
  33. } from '../../landing/widgets/widgetDefinitions';
  34. import {SetStateAction} from '../types';
  35. import AnomaliesTable from './anomaliesTable';
  36. import {AnomalyChart} from './anomalyChart';
  37. type Props = {
  38. eventView: EventView;
  39. location: Location;
  40. organization: Organization;
  41. projectId: string;
  42. setError: SetStateAction<string | undefined>;
  43. transactionName: string;
  44. };
  45. type AnomaliesSectionProps = Props & {
  46. queryData: ChildrenProps;
  47. };
  48. const anomalyAreaName = (anomaly: AnomalyInfo) => `#${anomaly.id}`;
  49. const transformAnomalyToArea = (
  50. anomaly: AnomalyInfo
  51. ): [{name: string; xAxis: number}, {xAxis: number}] => [
  52. {name: anomalyAreaName(anomaly), xAxis: anomaly.start},
  53. {xAxis: anomaly.end},
  54. ];
  55. const transformAnomalyData = (
  56. _: any,
  57. results: {data: AnomalyPayload; error: null | string; isLoading: boolean}
  58. ) => {
  59. const data: LineChartSeries[] = [];
  60. const resultData = results.data;
  61. if (!resultData) {
  62. return {
  63. isLoading: results.isLoading,
  64. isErrored: !!results.error,
  65. data: undefined,
  66. hasData: false,
  67. loading: results.isLoading,
  68. };
  69. }
  70. data.push({
  71. seriesName: 'tpm()',
  72. data: resultData.y.data.map(([name, [{count}]]) => ({
  73. name,
  74. value: count,
  75. })),
  76. });
  77. data.push({
  78. seriesName: 'tpm() lower bound',
  79. data: resultData.yhat_lower.data.map(([name, [{count}]]) => ({
  80. name,
  81. value: count,
  82. })),
  83. });
  84. data.push({
  85. seriesName: 'tpm() upper bound',
  86. data: resultData.yhat_upper.data.map(([name, [{count}]]) => ({
  87. name,
  88. value: count,
  89. })),
  90. });
  91. const anomalies = results.data.anomalies;
  92. const highConfidenceAreas = anomalies
  93. .filter(a => a.confidence === 'high')
  94. .map(transformAnomalyToArea);
  95. const highConfidenceLines = anomalies
  96. .filter(a => a.confidence === 'high')
  97. .map(area => ({xAxis: area.start, name: anomalyAreaName(area)}));
  98. const lowConfidenceAreas = anomalies
  99. .filter(a => a.confidence === 'low')
  100. .map(transformAnomalyToArea);
  101. const lowConfidenceLines = anomalies
  102. .filter(a => a.confidence === 'low')
  103. .map(area => ({xAxis: area.start, name: anomalyAreaName(area)}));
  104. data.push({
  105. seriesName: 'High Confidence',
  106. color: theme.red300,
  107. data: [],
  108. silent: true,
  109. markLine: MarkLine({
  110. animation: false,
  111. lineStyle: {color: theme.red300, type: 'solid', width: 1, opacity: 1.0},
  112. data: highConfidenceLines,
  113. label: {
  114. show: true,
  115. rotate: 90,
  116. color: theme.red300,
  117. position: 'insideEndBottom',
  118. fontSize: '10',
  119. offset: [5, 5],
  120. formatter: obj => `${(obj.data as any).name}`,
  121. },
  122. }),
  123. markArea: MarkArea({
  124. itemStyle: {
  125. color: theme.red300,
  126. opacity: 0.2,
  127. },
  128. label: {
  129. show: false,
  130. },
  131. data: highConfidenceAreas,
  132. }),
  133. });
  134. data.push({
  135. seriesName: 'Low Confidence',
  136. color: theme.yellow200,
  137. data: [],
  138. markLine: MarkLine({
  139. animation: false,
  140. lineStyle: {color: theme.yellow200, type: 'solid', width: 1, opacity: 1.0},
  141. data: lowConfidenceLines,
  142. label: {
  143. show: true,
  144. rotate: 90,
  145. color: theme.yellow300,
  146. position: 'insideEndBottom',
  147. fontSize: '10',
  148. offset: [5, 5],
  149. formatter: obj => `${(obj.data as any).name}`,
  150. },
  151. }),
  152. markArea: MarkArea({
  153. itemStyle: {
  154. color: theme.yellow200,
  155. opacity: 0.2,
  156. },
  157. label: {
  158. show: false,
  159. },
  160. data: lowConfidenceAreas,
  161. }),
  162. });
  163. return {
  164. isLoading: results.isLoading,
  165. isErrored: !!results.error,
  166. data,
  167. hasData: true,
  168. loading: results.isLoading,
  169. };
  170. };
  171. type AnomalyData = WidgetDataResult & ReturnType<typeof transformAnomalyData>;
  172. type DataType = {
  173. chart: AnomalyData;
  174. };
  175. function Anomalies(props: AnomaliesSectionProps) {
  176. const height = 250;
  177. const chartColor = theme.charts.colors[0];
  178. const chart = useMemo<QueryDefinition<DataType, WidgetDataResult>>(() => {
  179. return {
  180. fields: '',
  181. component: provided => <Fragment>{provided.children(props.queryData)}</Fragment>,
  182. transform: transformAnomalyData,
  183. };
  184. }, [props.queryData]);
  185. return (
  186. <GenericPerformanceWidget<DataType>
  187. {...props}
  188. title={t('Transaction Count')}
  189. titleTooltip={t(
  190. 'Represents transaction count across time, with added visualizations to highlight anomalies in your data.'
  191. )}
  192. fields={['']}
  193. chartSetting={PerformanceWidgetSetting.TPM_AREA}
  194. chartDefinition={WIDGET_DEFINITIONS[PerformanceWidgetSetting.TPM_AREA]}
  195. Subtitle={() => <div />}
  196. HeaderActions={() => <div />}
  197. EmptyComponent={WidgetEmptyStateWarning}
  198. Queries={{
  199. chart,
  200. }}
  201. Visualizations={[
  202. {
  203. component: provided => {
  204. const data =
  205. provided.widgetData.chart.data?.map(series => {
  206. if (series.seriesName !== 'tpm()') {
  207. series.lineStyle = {type: 'dashed', color: chartColor, width: 1.5};
  208. }
  209. if (series.seriesName === 'score') {
  210. series.lineStyle = {color: theme.red400};
  211. }
  212. return series;
  213. }) ?? [];
  214. return (
  215. <AnomalyChart
  216. {...provided}
  217. data={data}
  218. height={height}
  219. statsPeriod={undefined}
  220. start={null}
  221. end={null}
  222. />
  223. );
  224. },
  225. height,
  226. },
  227. ]}
  228. />
  229. );
  230. }
  231. function AnomaliesContent(props: Props) {
  232. const {location, organization, eventView} = props;
  233. const query = decodeScalar(location.query.query, '');
  234. function handleChange(key: string) {
  235. return function (value: string | undefined) {
  236. const queryParams = normalizeDateTimeParams({
  237. ...(location.query || {}),
  238. [key]: value,
  239. });
  240. // do not propagate pagination when making a new search
  241. const toOmit = ['cursor'];
  242. if (!defined(value)) {
  243. toOmit.push(key);
  244. }
  245. const searchQueryParams = omit(queryParams, toOmit);
  246. browserHistory.push({
  247. ...location,
  248. query: searchQueryParams,
  249. });
  250. };
  251. }
  252. return (
  253. <Layout.Main fullWidth>
  254. <FilterActions>
  255. <PageFilterBar condensed>
  256. <EnvironmentPageFilter />
  257. <DatePageFilter alignDropdown="left" />
  258. </PageFilterBar>
  259. <SearchBar
  260. organization={organization}
  261. projectIds={eventView.project}
  262. query={query}
  263. fields={eventView.fields}
  264. onSearch={handleChange('query')}
  265. />
  266. </FilterActions>
  267. <AnomaliesQuery
  268. organization={organization}
  269. location={location}
  270. eventView={eventView}
  271. >
  272. {queryData => (
  273. <Fragment>
  274. <AnomaliesWrapper>
  275. <Anomalies {...props} queryData={queryData} />
  276. </AnomaliesWrapper>
  277. <AnomaliesTable
  278. anomalies={queryData.data?.anomalies}
  279. {...props}
  280. isLoading={queryData.isLoading}
  281. />
  282. </Fragment>
  283. )}
  284. </AnomaliesQuery>
  285. </Layout.Main>
  286. );
  287. }
  288. const FilterActions = styled('div')`
  289. display: grid;
  290. gap: ${space(2)};
  291. margin-bottom: ${space(2)};
  292. @media (min-width: ${p => p.theme.breakpoints.small}) {
  293. grid-template-columns: auto 1fr;
  294. }
  295. `;
  296. const AnomaliesWrapper = styled('div')`
  297. margin-bottom: ${space(2)};
  298. `;
  299. export default AnomaliesContent;