sidebarCharts.tsx 12 KB

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