index.tsx 9.1 KB

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