index.tsx 9.1 KB

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