sidebarCharts.tsx 12 KB

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