sidebarCharts.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  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(
  146. ({name}) => (name as number) > (a.end + a.start) / 2
  147. )?.value,
  148. // TODO: the above is O(n*m), remove after we change the api to include the midpoint of y.
  149. xAxis: a.start,
  150. itemStyle: {
  151. borderColor: color(anomalyToColor(a.confidence, theme)).string(),
  152. color: color(anomalyToColor(a.confidence, theme))
  153. .alpha(0.2)
  154. .rgb()
  155. .string(),
  156. },
  157. onClick: () => {
  158. const target = anomaliesRouteWithQuery({
  159. orgSlug: organization.slug,
  160. query: location.query,
  161. projectID: decodeScalar(location.query.project),
  162. transaction: transactionName,
  163. });
  164. browserHistory.push(normalizeUrl(target));
  165. },
  166. })),
  167. symbol: 'circle',
  168. symbolSize: 16,
  169. });
  170. }
  171. }
  172. return (
  173. <TransitionChart loading={loading} reloading={reloading} height="580px">
  174. <TransparentLoadingMask visible={reloading} />
  175. {getDynamicText({
  176. value: (
  177. <LineChart {...zoomRenderProps} {...chartOptions} series={series} />
  178. ),
  179. fixed: <Placeholder height="300px" testId="skeleton-ui" />,
  180. })}
  181. </TransitionChart>
  182. );
  183. }}
  184. </ChartZoom>
  185. )}
  186. </AnomaliesQuery>
  187. </RelativeBox>
  188. );
  189. }
  190. function SidebarChartsContainer({
  191. eventView,
  192. organization,
  193. isLoading,
  194. error,
  195. totals,
  196. transactionName,
  197. }: ContainerProps) {
  198. const location = useLocation();
  199. const router = useRouter();
  200. const api = useApi();
  201. const theme = useTheme();
  202. const colors = theme.charts.getColorPalette(2);
  203. const statsPeriod = eventView.statsPeriod;
  204. const start = eventView.start ? getUtcToLocalDateObject(eventView.start) : undefined;
  205. const end = eventView.end ? getUtcToLocalDateObject(eventView.end) : undefined;
  206. const project = eventView.project;
  207. const environment = eventView.environment;
  208. const query = eventView.query;
  209. const utc = normalizeDateTimeParams(location.query).utc === 'true';
  210. const mepSetting = useMEPSettingContext();
  211. const queryExtras = getTransactionMEPParamsIfApplicable(mepSetting, organization);
  212. const axisLineConfig = {
  213. scale: true,
  214. axisLine: {
  215. show: false,
  216. },
  217. axisTick: {
  218. show: false,
  219. },
  220. splitLine: {
  221. show: false,
  222. },
  223. };
  224. const chartOptions: Omit<LineChartProps, 'series'> = {
  225. height: 300,
  226. grid: [
  227. {
  228. top: '60px',
  229. left: '10px',
  230. right: '10px',
  231. height: '100px',
  232. },
  233. {
  234. top: '220px',
  235. left: '10px',
  236. right: '10px',
  237. height: '100px',
  238. },
  239. ],
  240. axisPointer: {
  241. // Link each x-axis together.
  242. link: [{xAxisIndex: [0, 1]}],
  243. },
  244. xAxes: Array.from(new Array(2)).map((_i, index) => ({
  245. gridIndex: index,
  246. type: 'time',
  247. show: false,
  248. })),
  249. yAxes: [
  250. {
  251. // apdex
  252. gridIndex: 0,
  253. interval: 0.2,
  254. axisLabel: {
  255. formatter: (value: number) => `${formatFloat(value, 1)}`,
  256. color: theme.chartLabel,
  257. },
  258. ...axisLineConfig,
  259. },
  260. {
  261. // failure rate
  262. gridIndex: 1,
  263. splitNumber: 4,
  264. interval: 0.5,
  265. max: 1.0,
  266. axisLabel: {
  267. formatter: (value: number) => formatPercentage(value, 0),
  268. color: theme.chartLabel,
  269. },
  270. ...axisLineConfig,
  271. },
  272. ],
  273. utc,
  274. isGroupedByDate: true,
  275. showTimeInTooltip: true,
  276. colors: [colors[0], colors[1]],
  277. tooltip: {
  278. trigger: 'axis',
  279. truncate: 80,
  280. valueFormatter: (value, label) =>
  281. tooltipFormatter(value, aggregateOutputType(label)),
  282. nameFormatter(value: string) {
  283. return value === 'epm()' ? 'tpm()' : value;
  284. },
  285. },
  286. };
  287. const requestCommonProps = {
  288. api,
  289. start,
  290. end,
  291. period: statsPeriod,
  292. project,
  293. environment,
  294. query,
  295. };
  296. const contentCommonProps = {
  297. organization,
  298. router,
  299. error,
  300. isLoading,
  301. start,
  302. end,
  303. utc,
  304. totals,
  305. };
  306. const datetimeSelection = {
  307. start: start || null,
  308. end: end || null,
  309. period: statsPeriod,
  310. };
  311. return (
  312. <EventsRequest
  313. {...requestCommonProps}
  314. organization={organization}
  315. interval={getInterval(datetimeSelection)}
  316. showLoading={false}
  317. includePrevious={false}
  318. yAxis={['apdex()', 'failure_rate()']}
  319. partial
  320. referrer="api.performance.transaction-summary.sidebar-chart"
  321. queryExtras={queryExtras}
  322. >
  323. {({results, errored, loading, reloading}) => {
  324. const series = results
  325. ? results.map((v, i: number) => ({
  326. ...v,
  327. yAxisIndex: i,
  328. xAxisIndex: i,
  329. }))
  330. : [];
  331. return (
  332. <SidebarCharts
  333. {...contentCommonProps}
  334. transactionName={transactionName}
  335. eventView={eventView}
  336. chartData={{series, errored, loading, reloading, chartOptions}}
  337. />
  338. );
  339. }}
  340. </EventsRequest>
  341. );
  342. }
  343. type ChartValueProps = {
  344. 'data-test-id': string;
  345. error: QueryError | null;
  346. isLoading: boolean;
  347. value: React.ReactNode;
  348. };
  349. function ChartSummaryValue({error, isLoading, value, ...props}: ChartValueProps) {
  350. if (error) {
  351. return <div {...props}>{'\u2014'}</div>;
  352. }
  353. if (isLoading) {
  354. return <Placeholder height="24px" {...props} />;
  355. }
  356. return <ChartValue {...props}>{value}</ChartValue>;
  357. }
  358. const RelativeBox = styled('div')`
  359. position: relative;
  360. `;
  361. const ChartTitle = styled(SectionHeading)`
  362. margin: 0;
  363. `;
  364. const ChartLabel = styled('div')<{top: string}>`
  365. position: absolute;
  366. top: ${p => p.top};
  367. z-index: 1;
  368. `;
  369. const ChartValue = styled('div')`
  370. font-size: ${p => p.theme.fontSizeExtraLarge};
  371. `;
  372. export default SidebarChartsContainer;