index.tsx 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  143. scale = (unit && (DURATION_UNITS[unit] ?? SIZE_UNITS[unit])) ?? 1;
  144. }
  145. return [
  146. {
  147. seriesName,
  148. data: data.map(([timestamp, countsForTimestamp]) => ({
  149. name: timestamp * 1000,
  150. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0) * scale,
  151. })),
  152. },
  153. ];
  154. }
  155. return (
  156. <Fragment>
  157. {header}
  158. {shouldGetBreakpoint ? (
  159. // queries events-trends-statsv2 for breakpoint data (feature flag only)
  160. <TrendsDiscoverQuery
  161. eventView={trendView}
  162. orgSlug={organization.slug}
  163. location={location}
  164. limit={1}
  165. withBreakpoint
  166. >
  167. {({isLoading, trendsData}) => {
  168. const events = normalizeTrends(trendsData?.events?.data || []);
  169. // keep trend change type as regression until the backend can support passing the type
  170. const selectedTransaction = getSelectedTransaction(
  171. location,
  172. TrendChangeType.ANY,
  173. events
  174. );
  175. const statsData = trendsData?.stats || {};
  176. const transactionEvent = (
  177. statsData &&
  178. selectedTransaction?.project &&
  179. selectedTransaction?.transaction
  180. ? statsData[
  181. [selectedTransaction?.project, selectedTransaction?.transaction].join(
  182. ','
  183. )
  184. ]
  185. : undefined
  186. ) as EventsStats;
  187. const data = transactionEvent?.data ?? [];
  188. const meta = transactionEvent?.meta ?? ({} as EventsStats['meta']);
  189. const timeSeriesMetricsData = transformTimeseriesData(
  190. data,
  191. meta,
  192. trendDisplay
  193. );
  194. const metricsTimeFrame =
  195. transactionEvent?.start && transactionEvent.end
  196. ? {start: transactionEvent.start * 1000, end: transactionEvent.end * 1000}
  197. : undefined;
  198. return data.length !== 0 ? (
  199. <Content
  200. series={timeSeriesMetricsData}
  201. errored={!trendsData && !isLoading}
  202. loading={isLoading || isCardinalityCheckLoading}
  203. reloading={isLoading}
  204. timeFrame={metricsTimeFrame}
  205. withBreakpoint
  206. transaction={selectedTransaction}
  207. {...contentCommonProps}
  208. />
  209. ) : (
  210. // queries events-stats for trend data if metrics trend data not found
  211. <EventsRequest
  212. {...requestCommonProps}
  213. organization={organization}
  214. showLoading={false}
  215. includePrevious={false}
  216. yAxis={trendDisplay}
  217. currentSeriesNames={[trendDisplay]}
  218. partial
  219. withoutZerofill={withoutZerofill}
  220. referrer="api.performance.transaction-summary.trends-chart"
  221. >
  222. {({errored, loading, reloading, timeseriesData, timeframe}) => {
  223. return (
  224. <Content
  225. series={timeseriesData}
  226. errored={errored}
  227. loading={loading || isLoading}
  228. reloading={reloading}
  229. timeFrame={timeframe}
  230. withBreakpoint
  231. transaction={selectedTransaction}
  232. {...contentCommonProps}
  233. />
  234. );
  235. }}
  236. </EventsRequest>
  237. );
  238. }}
  239. </TrendsDiscoverQuery>
  240. ) : (
  241. <EventsRequest
  242. {...requestCommonProps}
  243. organization={organization}
  244. showLoading={false}
  245. includePrevious={false}
  246. yAxis={trendDisplay}
  247. currentSeriesNames={[trendDisplay]}
  248. partial
  249. withoutZerofill={withoutZerofill}
  250. referrer="api.performance.transaction-summary.trends-chart"
  251. >
  252. {({errored, loading, reloading, timeseriesData, timeframe: timeFrame}) => {
  253. return (
  254. <Content
  255. series={timeseriesData}
  256. errored={errored}
  257. loading={loading || isCardinalityCheckLoading}
  258. reloading={reloading}
  259. timeFrame={timeFrame}
  260. {...contentCommonProps}
  261. />
  262. );
  263. }}
  264. </EventsRequest>
  265. )}
  266. </Fragment>
  267. );
  268. }
  269. export default TrendChart;