sidebarCharts.tsx 12 KB

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