sidebarCharts.tsx 12 KB

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