sidebarCharts.tsx 12 KB

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