index.tsx 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. import {Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {useTheme} from '@emotion/react';
  4. import type {Query} from 'history';
  5. import EventsRequest from 'sentry/components/charts/eventsRequest';
  6. import {HeaderTitleLegend} from 'sentry/components/charts/styles';
  7. import {getInterval, getSeriesSelection} from 'sentry/components/charts/utils';
  8. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  9. import QuestionTooltip from 'sentry/components/questionTooltip';
  10. import {t} from 'sentry/locale';
  11. import type {
  12. EventsStats,
  13. EventsStatsData,
  14. OrganizationSummary,
  15. Project,
  16. } from 'sentry/types';
  17. import type {Series} from 'sentry/types/echarts';
  18. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  19. import type EventView from 'sentry/utils/discover/eventView';
  20. import {DURATION_UNITS, SIZE_UNITS} from 'sentry/utils/discover/fieldRenderers';
  21. import {getAggregateAlias} from 'sentry/utils/discover/fields';
  22. import {useMetricsCardinalityContext} from 'sentry/utils/performance/contexts/metricsCardinality';
  23. import TrendsDiscoverQuery from 'sentry/utils/performance/trends/trendsDiscoverQuery';
  24. import useApi from 'sentry/utils/useApi';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useRouter from 'sentry/utils/useRouter';
  27. import type {TrendFunctionField, TrendView} from 'sentry/views/performance/trends/types';
  28. import {TrendChangeType} from 'sentry/views/performance/trends/types';
  29. import {
  30. generateTrendFunctionAsString,
  31. modifyTrendView,
  32. normalizeTrends,
  33. } from 'sentry/views/performance/trends/utils';
  34. import type {ViewProps} from 'sentry/views/performance/types';
  35. import {getSelectedTransaction} from 'sentry/views/performance/utils';
  36. import Content from './content';
  37. type Props = ViewProps & {
  38. eventView: EventView;
  39. organization: OrganizationSummary;
  40. projects: Project[];
  41. queryExtra: Query;
  42. trendFunction: TrendFunctionField;
  43. trendParameter: string;
  44. withoutZerofill: boolean;
  45. withBreakpoint?: boolean;
  46. };
  47. function TrendChart({
  48. project,
  49. environment,
  50. organization,
  51. query,
  52. statsPeriod,
  53. trendFunction,
  54. trendParameter,
  55. queryExtra,
  56. withoutZerofill,
  57. withBreakpoint,
  58. eventView,
  59. start: propsStart,
  60. end: propsEnd,
  61. projects,
  62. }: Props) {
  63. const router = useRouter();
  64. const location = useLocation();
  65. const api = useApi();
  66. const theme = useTheme();
  67. const {isLoading: isCardinalityCheckLoading, outcome} = useMetricsCardinalityContext();
  68. const shouldGetBreakpoint =
  69. withBreakpoint && !isCardinalityCheckLoading && !outcome?.forceTransactionsOnly;
  70. function handleLegendSelectChanged(legendChange: {
  71. name: string;
  72. selected: Record<string, boolean>;
  73. type: string;
  74. }) {
  75. const {selected} = legendChange;
  76. const unselected = Object.keys(selected).filter(key => !selected[key]);
  77. const to = {
  78. ...location,
  79. query: {
  80. ...location.query,
  81. unselectedSeries: unselected,
  82. },
  83. };
  84. browserHistory.push(to);
  85. }
  86. const start = propsStart ? getUtcToLocalDateObject(propsStart) : null;
  87. const end = propsEnd ? getUtcToLocalDateObject(propsEnd) : null;
  88. const utc = normalizeDateTimeParams(location.query)?.utc === 'true';
  89. const period = statsPeriod;
  90. const legend = {
  91. right: 10,
  92. top: 0,
  93. selected: getSeriesSelection(location),
  94. };
  95. const datetimeSelection = {start, end, period};
  96. const contentCommonProps = {
  97. theme,
  98. router,
  99. start,
  100. end,
  101. utc,
  102. legend,
  103. queryExtra,
  104. period,
  105. projects: project,
  106. environments: environment,
  107. onLegendSelectChanged: handleLegendSelectChanged,
  108. };
  109. const requestCommonProps = {
  110. api,
  111. start,
  112. end,
  113. project,
  114. environment,
  115. query,
  116. period,
  117. interval: getInterval(datetimeSelection, 'high'),
  118. };
  119. const header = (
  120. <HeaderTitleLegend>
  121. {t('Trend')}
  122. <QuestionTooltip
  123. size="sm"
  124. position="top"
  125. title={t('Trends shows the smoothed value of an aggregate over time.')}
  126. />
  127. </HeaderTitleLegend>
  128. );
  129. const trendDisplay = generateTrendFunctionAsString(trendFunction, trendParameter);
  130. const trendView = eventView.clone() as TrendView;
  131. modifyTrendView(
  132. trendView,
  133. location,
  134. TrendChangeType.ANY,
  135. projects,
  136. shouldGetBreakpoint
  137. );
  138. function transformTimeseriesData(
  139. data: EventsStatsData,
  140. meta: EventsStats['meta'],
  141. seriesName: string
  142. ): Series[] {
  143. let scale = 1;
  144. if (seriesName) {
  145. const unit = meta?.units?.[getAggregateAlias(seriesName)];
  146. // Scale series values to milliseconds or bytes depending on units from meta
  147. scale = (unit && (DURATION_UNITS[unit] ?? SIZE_UNITS[unit])) ?? 1;
  148. }
  149. return [
  150. {
  151. seriesName,
  152. data: data.map(([timestamp, countsForTimestamp]) => ({
  153. name: timestamp * 1000,
  154. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0) * scale,
  155. })),
  156. },
  157. ];
  158. }
  159. return (
  160. <Fragment>
  161. {header}
  162. {shouldGetBreakpoint ? (
  163. // queries events-trends-statsv2 for breakpoint data (feature flag only)
  164. <TrendsDiscoverQuery
  165. eventView={trendView}
  166. orgSlug={organization.slug}
  167. location={location}
  168. limit={1}
  169. withBreakpoint
  170. >
  171. {({isLoading, trendsData}) => {
  172. const events = normalizeTrends(trendsData?.events?.data || []);
  173. // keep trend change type as regression until the backend can support passing the type
  174. const selectedTransaction = getSelectedTransaction(
  175. location,
  176. TrendChangeType.ANY,
  177. events
  178. );
  179. const statsData = trendsData?.stats || {};
  180. const transactionEvent = (
  181. statsData &&
  182. selectedTransaction?.project &&
  183. selectedTransaction?.transaction
  184. ? statsData[
  185. [selectedTransaction?.project, selectedTransaction?.transaction].join(
  186. ','
  187. )
  188. ]
  189. : undefined
  190. ) as EventsStats;
  191. const data = transactionEvent?.data ?? [];
  192. const meta = transactionEvent?.meta ?? ({} as EventsStats['meta']);
  193. const timeSeriesMetricsData = transformTimeseriesData(
  194. data,
  195. meta,
  196. trendDisplay
  197. );
  198. const metricsTimeFrame =
  199. transactionEvent?.start && transactionEvent.end
  200. ? {start: transactionEvent.start * 1000, end: transactionEvent.end * 1000}
  201. : undefined;
  202. return data.length !== 0 ? (
  203. <Content
  204. series={timeSeriesMetricsData}
  205. errored={!trendsData && !isLoading}
  206. loading={isLoading || isCardinalityCheckLoading}
  207. reloading={isLoading}
  208. timeFrame={metricsTimeFrame}
  209. withBreakpoint
  210. transaction={selectedTransaction}
  211. {...contentCommonProps}
  212. />
  213. ) : (
  214. // queries events-stats for trend data if metrics trend data not found
  215. <EventsRequest
  216. {...requestCommonProps}
  217. organization={organization}
  218. showLoading={false}
  219. includePrevious={false}
  220. yAxis={trendDisplay}
  221. currentSeriesNames={[trendDisplay]}
  222. partial
  223. withoutZerofill={withoutZerofill}
  224. referrer="api.performance.transaction-summary.trends-chart"
  225. >
  226. {({errored, loading, reloading, timeseriesData, timeframe}) => {
  227. return (
  228. <Content
  229. series={timeseriesData}
  230. errored={errored}
  231. loading={loading || isLoading}
  232. reloading={reloading}
  233. timeFrame={timeframe}
  234. withBreakpoint
  235. transaction={selectedTransaction}
  236. {...contentCommonProps}
  237. />
  238. );
  239. }}
  240. </EventsRequest>
  241. );
  242. }}
  243. </TrendsDiscoverQuery>
  244. ) : (
  245. <EventsRequest
  246. {...requestCommonProps}
  247. organization={organization}
  248. showLoading={false}
  249. includePrevious={false}
  250. yAxis={trendDisplay}
  251. currentSeriesNames={[trendDisplay]}
  252. partial
  253. withoutZerofill={withoutZerofill}
  254. referrer="api.performance.transaction-summary.trends-chart"
  255. >
  256. {({errored, loading, reloading, timeseriesData, timeframe: timeFrame}) => {
  257. return (
  258. <Content
  259. series={timeseriesData}
  260. errored={errored}
  261. loading={loading || isCardinalityCheckLoading}
  262. reloading={reloading}
  263. timeFrame={timeFrame}
  264. {...contentCommonProps}
  265. />
  266. );
  267. }}
  268. </EventsRequest>
  269. )}
  270. </Fragment>
  271. );
  272. }
  273. export default TrendChart;