sidebarCharts.tsx 11 KB

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