sidebarCharts.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. import {browserHistory} from 'react-router';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import color from 'color';
  5. import ChartZoom from 'sentry/components/charts/chartZoom';
  6. import MarkPoint from 'sentry/components/charts/components/markPoint';
  7. import ErrorPanel from 'sentry/components/charts/errorPanel';
  8. import EventsRequest from 'sentry/components/charts/eventsRequest';
  9. import {LineChart, LineChartProps} from 'sentry/components/charts/lineChart';
  10. import {SectionHeading} from 'sentry/components/charts/styles';
  11. import TransitionChart from 'sentry/components/charts/transitionChart';
  12. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  13. import {getInterval} from 'sentry/components/charts/utils';
  14. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  15. import Placeholder from 'sentry/components/placeholder';
  16. import QuestionTooltip from 'sentry/components/questionTooltip';
  17. import {IconWarning} from 'sentry/icons';
  18. import {t, tct} from 'sentry/locale';
  19. import {Organization} from 'sentry/types';
  20. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  21. import {tooltipFormatter} from 'sentry/utils/discover/charts';
  22. import EventView from 'sentry/utils/discover/eventView';
  23. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  24. import {QueryError} from 'sentry/utils/discover/genericDiscoverQuery';
  25. import {
  26. formatAbbreviatedNumber,
  27. formatFloat,
  28. formatPercentage,
  29. } from 'sentry/utils/formatters';
  30. import getDynamicText from 'sentry/utils/getDynamicText';
  31. import AnomaliesQuery from 'sentry/utils/performance/anomalies/anomaliesQuery';
  32. import {useMEPSettingContext} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  33. import {decodeScalar} from 'sentry/utils/queryString';
  34. import useApi from 'sentry/utils/useApi';
  35. import {useLocation} from 'sentry/utils/useLocation';
  36. import useRouter from 'sentry/utils/useRouter';
  37. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  38. import {getTermHelp, PERFORMANCE_TERM} from 'sentry/views/performance/data';
  39. import {getTransactionMEPParamsIfApplicable} from 'sentry/views/performance/transactionSummary/transactionOverview/utils';
  40. import {
  41. anomaliesRouteWithQuery,
  42. ANOMALY_FLAG,
  43. anomalyToColor,
  44. } from '../transactionAnomalies/utils';
  45. type ContainerProps = {
  46. error: QueryError | null;
  47. eventView: EventView;
  48. isLoading: boolean;
  49. organization: Organization;
  50. totals: Record<string, number> | null;
  51. transactionName: string;
  52. unfilteredTotals?: Record<string, number> | null;
  53. };
  54. type Props = Pick<
  55. ContainerProps,
  56. 'organization' | 'isLoading' | 'error' | 'totals' | 'unfilteredTotals'
  57. > & {
  58. chartData: {
  59. chartOptions: Omit<LineChartProps, 'series'>;
  60. errored: boolean;
  61. loading: boolean;
  62. reloading: boolean;
  63. series: LineChartProps['series'];
  64. };
  65. eventView: EventView;
  66. transactionName: string;
  67. utc: boolean;
  68. end?: Date;
  69. start?: Date;
  70. statsPeriod?: string | null;
  71. };
  72. function SidebarCharts({
  73. organization,
  74. isLoading,
  75. error,
  76. totals,
  77. start,
  78. end,
  79. utc,
  80. statsPeriod,
  81. chartData,
  82. eventView,
  83. transactionName,
  84. unfilteredTotals,
  85. }: Props) {
  86. const location = useLocation();
  87. const router = useRouter();
  88. const theme = useTheme();
  89. const displayTPMAsPercentage = !!unfilteredTotals;
  90. function getValueFromTotals(field, totalValues, unfilteredTotalValues) {
  91. if (totalValues) {
  92. if (unfilteredTotalValues) {
  93. return tct('[tpm]', {
  94. tpm: formatPercentage(totalValues[field] / unfilteredTotalValues[field]),
  95. });
  96. }
  97. return tct('[tpm] tpm', {
  98. tpm: formatFloat(totalValues[field], 4),
  99. });
  100. }
  101. return null;
  102. }
  103. return (
  104. <RelativeBox>
  105. <ChartLabel top="0px">
  106. <ChartTitle>
  107. {t('Apdex')}
  108. <QuestionTooltip
  109. position="top"
  110. title={getTermHelp(organization, PERFORMANCE_TERM.APDEX)}
  111. size="sm"
  112. />
  113. </ChartTitle>
  114. <ChartSummaryValue
  115. data-test-id="apdex-summary-value"
  116. isLoading={isLoading}
  117. error={error}
  118. value={totals ? formatFloat(totals['apdex()'], 4) : null}
  119. />
  120. </ChartLabel>
  121. <ChartLabel top="160px">
  122. <ChartTitle>
  123. {t('Failure Rate')}
  124. <QuestionTooltip
  125. position="top"
  126. title={getTermHelp(organization, PERFORMANCE_TERM.FAILURE_RATE)}
  127. size="sm"
  128. />
  129. </ChartTitle>
  130. <ChartSummaryValue
  131. data-test-id="failure-rate-summary-value"
  132. isLoading={isLoading}
  133. error={error}
  134. value={totals ? formatPercentage(totals['failure_rate()']) : null}
  135. />
  136. </ChartLabel>
  137. <ChartLabel top="320px">
  138. <ChartTitle>
  139. {displayTPMAsPercentage ? t('Total Events') : t('TPM')}
  140. <QuestionTooltip
  141. position="top"
  142. title={
  143. displayTPMAsPercentage
  144. ? tct('[count] events', {
  145. count: unfilteredTotals['count()'].toLocaleString(),
  146. })
  147. : getTermHelp(organization, PERFORMANCE_TERM.TPM)
  148. }
  149. size="sm"
  150. />
  151. </ChartTitle>
  152. <ChartSummaryValue
  153. data-test-id="tpm-summary-value"
  154. isLoading={isLoading}
  155. error={error}
  156. value={getValueFromTotals('tpm()', totals, unfilteredTotals)}
  157. />
  158. </ChartLabel>
  159. <AnomaliesQuery
  160. location={location}
  161. organization={organization}
  162. eventView={eventView}
  163. >
  164. {results => (
  165. <ChartZoom
  166. router={router}
  167. period={statsPeriod}
  168. start={start}
  169. end={end}
  170. utc={utc}
  171. xAxisIndex={[0, 1, 2]}
  172. >
  173. {zoomRenderProps => {
  174. const {errored, loading, reloading, chartOptions, series} = chartData;
  175. if (errored) {
  176. return (
  177. <ErrorPanel height="580px">
  178. <IconWarning color="gray300" size="lg" />
  179. </ErrorPanel>
  180. );
  181. }
  182. if (organization.features.includes(ANOMALY_FLAG)) {
  183. const epmSeries = series.find(
  184. s => s.seriesName.includes('epm') || s.seriesName.includes('tpm')
  185. );
  186. if (epmSeries && results.data) {
  187. epmSeries.markPoint = MarkPoint({
  188. data: results.data.anomalies.map(a => ({
  189. name: a.id,
  190. yAxis: epmSeries.data.find(({name}) => name > (a.end + a.start) / 2)
  191. ?.value,
  192. // TODO: the above is O(n*m), remove after we change the api to include the midpoint of y.
  193. xAxis: a.start,
  194. itemStyle: {
  195. borderColor: color(anomalyToColor(a.confidence, theme)).string(),
  196. color: color(anomalyToColor(a.confidence, theme))
  197. .alpha(0.2)
  198. .rgb()
  199. .string(),
  200. },
  201. onClick: () => {
  202. const target = anomaliesRouteWithQuery({
  203. orgSlug: organization.slug,
  204. query: location.query,
  205. projectID: decodeScalar(location.query.project),
  206. transaction: transactionName,
  207. });
  208. browserHistory.push(normalizeUrl(target));
  209. },
  210. })),
  211. symbol: 'circle',
  212. symbolSize: 16,
  213. });
  214. }
  215. }
  216. return (
  217. <TransitionChart loading={loading} reloading={reloading} height="580px">
  218. <TransparentLoadingMask visible={reloading} />
  219. {getDynamicText({
  220. value: (
  221. <LineChart {...zoomRenderProps} {...chartOptions} series={series} />
  222. ),
  223. fixed: <Placeholder height="480px" testId="skeleton-ui" />,
  224. })}
  225. </TransitionChart>
  226. );
  227. }}
  228. </ChartZoom>
  229. )}
  230. </AnomaliesQuery>
  231. </RelativeBox>
  232. );
  233. }
  234. function SidebarChartsContainer({
  235. eventView,
  236. organization,
  237. isLoading,
  238. error,
  239. totals,
  240. transactionName,
  241. unfilteredTotals,
  242. }: ContainerProps) {
  243. const location = useLocation();
  244. const router = useRouter();
  245. const api = useApi();
  246. const theme = useTheme();
  247. const colors = theme.charts.getColorPalette(3);
  248. const statsPeriod = eventView.statsPeriod;
  249. const start = eventView.start ? getUtcToLocalDateObject(eventView.start) : undefined;
  250. const end = eventView.end ? getUtcToLocalDateObject(eventView.end) : undefined;
  251. const project = eventView.project;
  252. const environment = eventView.environment;
  253. const query = eventView.query;
  254. const utc = normalizeDateTimeParams(location.query).utc === 'true';
  255. const mepSetting = useMEPSettingContext();
  256. const queryExtras = getTransactionMEPParamsIfApplicable(
  257. mepSetting,
  258. organization,
  259. location
  260. );
  261. const axisLineConfig = {
  262. scale: true,
  263. axisLine: {
  264. show: false,
  265. },
  266. axisTick: {
  267. show: false,
  268. },
  269. splitLine: {
  270. show: false,
  271. },
  272. };
  273. const chartOptions: Omit<LineChartProps, 'series'> = {
  274. height: 360,
  275. grid: [
  276. {
  277. top: '60px',
  278. left: '10px',
  279. right: '10px',
  280. height: '100px',
  281. },
  282. {
  283. top: '220px',
  284. left: '10px',
  285. right: '10px',
  286. height: '100px',
  287. },
  288. {
  289. top: '380px',
  290. left: '10px',
  291. right: '10px',
  292. height: '0px',
  293. },
  294. ],
  295. axisPointer: {
  296. // Link each x-axis together.
  297. link: [{xAxisIndex: [0, 1, 2]}],
  298. },
  299. xAxes: Array.from(new Array(3)).map((_i, index) => ({
  300. gridIndex: index,
  301. type: 'time',
  302. show: false,
  303. })),
  304. yAxes: [
  305. {
  306. // apdex
  307. gridIndex: 0,
  308. interval: 0.2,
  309. axisLabel: {
  310. formatter: (value: number) => `${formatFloat(value, 1)}`,
  311. color: theme.chartLabel,
  312. },
  313. ...axisLineConfig,
  314. },
  315. {
  316. // failure rate
  317. gridIndex: 1,
  318. splitNumber: 4,
  319. interval: 0.5,
  320. max: 1.0,
  321. axisLabel: {
  322. formatter: (value: number) => formatPercentage(value, 0),
  323. color: theme.chartLabel,
  324. },
  325. ...axisLineConfig,
  326. },
  327. {
  328. // throughput
  329. gridIndex: 2,
  330. splitNumber: 4,
  331. axisLabel: {
  332. formatter: value =>
  333. unfilteredTotals
  334. ? formatPercentage(value, 0)
  335. : formatAbbreviatedNumber(value),
  336. color: theme.chartLabel,
  337. },
  338. ...axisLineConfig,
  339. },
  340. ],
  341. utc,
  342. isGroupedByDate: true,
  343. showTimeInTooltip: true,
  344. colors: [colors[0], colors[1], colors[2]],
  345. tooltip: {
  346. trigger: 'axis',
  347. truncate: 80,
  348. valueFormatter: (value, label) => {
  349. const shouldUsePercentageForTPM = unfilteredTotals && label === 'epm()';
  350. return shouldUsePercentageForTPM
  351. ? tooltipFormatter(value, 'percentage')
  352. : tooltipFormatter(value, aggregateOutputType(label));
  353. },
  354. nameFormatter(value: string) {
  355. return value === 'epm()' ? 'tpm()' : value;
  356. },
  357. },
  358. };
  359. const requestCommonProps = {
  360. api,
  361. start,
  362. end,
  363. period: statsPeriod,
  364. project,
  365. environment,
  366. query,
  367. };
  368. const contentCommonProps = {
  369. organization,
  370. router,
  371. error,
  372. isLoading,
  373. start,
  374. end,
  375. utc,
  376. totals,
  377. unfilteredTotals,
  378. };
  379. const datetimeSelection = {
  380. start: start || null,
  381. end: end || null,
  382. period: statsPeriod,
  383. };
  384. return (
  385. <EventsRequest
  386. {...requestCommonProps}
  387. organization={organization}
  388. interval={getInterval(datetimeSelection)}
  389. showLoading={false}
  390. includePrevious={false}
  391. yAxis={['apdex()', 'failure_rate()']}
  392. partial
  393. referrer="api.performance.transaction-summary.sidebar-chart"
  394. queryExtras={queryExtras}
  395. >
  396. {({results, errored, loading, reloading}) => {
  397. const series = results
  398. ? results.map((v, i: number) => ({
  399. ...v,
  400. yAxisIndex: i,
  401. xAxisIndex: i,
  402. }))
  403. : [];
  404. return (
  405. <SidebarCharts
  406. {...contentCommonProps}
  407. transactionName={transactionName}
  408. eventView={eventView}
  409. chartData={{series, errored, loading, reloading, chartOptions}}
  410. />
  411. );
  412. }}
  413. </EventsRequest>
  414. );
  415. }
  416. type ChartValueProps = {
  417. 'data-test-id': string;
  418. error: QueryError | null;
  419. isLoading: boolean;
  420. value: React.ReactNode;
  421. };
  422. function ChartSummaryValue({error, isLoading, value, ...props}: ChartValueProps) {
  423. if (error) {
  424. return <div {...props}>{'\u2014'}</div>;
  425. }
  426. if (isLoading) {
  427. return <Placeholder height="24px" {...props} />;
  428. }
  429. return <ChartValue {...props}>{value}</ChartValue>;
  430. }
  431. const RelativeBox = styled('div')`
  432. position: relative;
  433. `;
  434. const ChartTitle = styled(SectionHeading)`
  435. margin: 0;
  436. `;
  437. const ChartLabel = styled('div')<{top: string}>`
  438. position: absolute;
  439. top: ${p => p.top};
  440. z-index: 1;
  441. `;
  442. const ChartValue = styled('div')`
  443. font-size: ${p => p.theme.fontSizeExtraLarge};
  444. `;
  445. export default SidebarChartsContainer;