sidebarCharts.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. import {useTheme} from '@emotion/react';
  2. import styled from '@emotion/styled';
  3. import color from 'color';
  4. import ChartZoom from 'sentry/components/charts/chartZoom';
  5. import MarkPoint from 'sentry/components/charts/components/markPoint';
  6. import ErrorPanel from 'sentry/components/charts/errorPanel';
  7. import EventsRequest from 'sentry/components/charts/eventsRequest';
  8. import type {LineChartProps} from 'sentry/components/charts/lineChart';
  9. import {LineChart} 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 type {Organization} from 'sentry/types/organization';
  20. import {browserHistory} from 'sentry/utils/browserHistory';
  21. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  22. import {tooltipFormatter} from 'sentry/utils/discover/charts';
  23. import type EventView from 'sentry/utils/discover/eventView';
  24. import {aggregateOutputType} from 'sentry/utils/discover/fields';
  25. import type {QueryError} from 'sentry/utils/discover/genericDiscoverQuery';
  26. import getDynamicText from 'sentry/utils/getDynamicText';
  27. import {formatFloat} from 'sentry/utils/number/formatFloat';
  28. import {formatPercentage} from 'sentry/utils/number/formatPercentage';
  29. import AnomaliesQuery from 'sentry/utils/performance/anomalies/anomaliesQuery';
  30. import {useMetricsCardinalityContext} from 'sentry/utils/performance/contexts/metricsCardinality';
  31. import {useMEPSettingContext} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  32. import {decodeScalar} from 'sentry/utils/queryString';
  33. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  34. import useApi from 'sentry/utils/useApi';
  35. import {useLocation} from 'sentry/utils/useLocation';
  36. import {getTermHelp, PerformanceTerm} from 'sentry/views/performance/data';
  37. import {getTransactionMEPParamsIfApplicable} from 'sentry/views/performance/transactionSummary/transactionOverview/utils';
  38. import {
  39. anomaliesRouteWithQuery,
  40. ANOMALY_FLAG,
  41. anomalyToColor,
  42. } from '../transactionAnomalies/utils';
  43. type ContainerProps = {
  44. error: QueryError | null;
  45. eventView: EventView;
  46. isLoading: boolean;
  47. organization: Organization;
  48. totals: Record<string, number> | null;
  49. transactionName: string;
  50. };
  51. type Props = Pick<ContainerProps, 'organization' | 'isLoading' | 'error' | 'totals'> & {
  52. chartData: {
  53. chartOptions: Omit<LineChartProps, 'series'>;
  54. errored: boolean;
  55. loading: boolean;
  56. reloading: boolean;
  57. series: LineChartProps['series'];
  58. };
  59. eventView: EventView;
  60. transactionName: string;
  61. utc: boolean;
  62. end?: Date;
  63. start?: Date;
  64. statsPeriod?: string | null;
  65. };
  66. function SidebarCharts({
  67. organization,
  68. isLoading,
  69. error,
  70. totals,
  71. start,
  72. end,
  73. utc,
  74. statsPeriod,
  75. chartData,
  76. eventView,
  77. transactionName,
  78. }: Props) {
  79. const location = useLocation();
  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. 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 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 mepCardinalityContext = useMetricsCardinalityContext();
  211. const queryExtras = getTransactionMEPParamsIfApplicable(
  212. mepSetting,
  213. mepCardinalityContext,
  214. organization
  215. );
  216. const axisLineConfig = {
  217. scale: true,
  218. axisLine: {
  219. show: false,
  220. },
  221. axisTick: {
  222. show: false,
  223. },
  224. splitLine: {
  225. show: false,
  226. },
  227. };
  228. const chartOptions: Omit<LineChartProps, 'series'> = {
  229. height: 300,
  230. grid: [
  231. {
  232. top: '60px',
  233. left: '10px',
  234. right: '10px',
  235. height: '100px',
  236. },
  237. {
  238. top: '220px',
  239. left: '10px',
  240. right: '10px',
  241. height: '100px',
  242. },
  243. ],
  244. axisPointer: {
  245. // Link each x-axis together.
  246. link: [{xAxisIndex: [0, 1]}],
  247. },
  248. xAxes: Array.from(new Array(2)).map((_i, index) => ({
  249. gridIndex: index,
  250. type: 'time',
  251. show: false,
  252. })),
  253. yAxes: [
  254. {
  255. // apdex
  256. gridIndex: 0,
  257. interval: 0.2,
  258. axisLabel: {
  259. formatter: (value: number) => `${formatFloat(value, 1)}`,
  260. color: theme.chartLabel,
  261. },
  262. ...axisLineConfig,
  263. },
  264. {
  265. // failure rate
  266. gridIndex: 1,
  267. splitNumber: 4,
  268. interval: 0.5,
  269. max: 1.0,
  270. axisLabel: {
  271. formatter: (value: number) => formatPercentage(value, 0),
  272. color: theme.chartLabel,
  273. },
  274. ...axisLineConfig,
  275. },
  276. ],
  277. utc,
  278. isGroupedByDate: true,
  279. showTimeInTooltip: true,
  280. colors: [colors[0], colors[1]],
  281. tooltip: {
  282. trigger: 'axis',
  283. truncate: 80,
  284. valueFormatter: (value, label) =>
  285. tooltipFormatter(value, aggregateOutputType(label)),
  286. nameFormatter(value: string) {
  287. return value === 'epm()' ? 'tpm()' : value;
  288. },
  289. },
  290. };
  291. const requestCommonProps = {
  292. api,
  293. start,
  294. end,
  295. period: statsPeriod,
  296. project,
  297. environment,
  298. query,
  299. };
  300. const contentCommonProps = {
  301. organization,
  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;