sidebarCharts.tsx 12 KB

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