index.tsx 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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(
  173. (trendsData && trendsData.events && trendsData.events.data) || []
  174. );
  175. // keep trend change type as regression until the backend can support passing the type
  176. const selectedTransaction = getSelectedTransaction(
  177. location,
  178. TrendChangeType.ANY,
  179. events
  180. );
  181. const statsData = trendsData?.stats || {};
  182. const transactionEvent = (
  183. statsData &&
  184. selectedTransaction?.project &&
  185. selectedTransaction?.transaction
  186. ? statsData[
  187. [selectedTransaction?.project, selectedTransaction?.transaction].join(
  188. ','
  189. )
  190. ]
  191. : undefined
  192. ) as EventsStats;
  193. const data = transactionEvent?.data ?? [];
  194. const meta = transactionEvent?.meta ?? ({} as EventsStats['meta']);
  195. const timeSeriesMetricsData = transformTimeseriesData(
  196. data,
  197. meta,
  198. trendDisplay
  199. );
  200. const metricsTimeFrame =
  201. transactionEvent && transactionEvent.start && transactionEvent.end
  202. ? {start: transactionEvent.start * 1000, end: transactionEvent.end * 1000}
  203. : undefined;
  204. return data.length !== 0 ? (
  205. <Content
  206. series={timeSeriesMetricsData}
  207. errored={!trendsData && !isLoading}
  208. loading={isLoading || isCardinalityCheckLoading}
  209. reloading={isLoading}
  210. timeFrame={metricsTimeFrame}
  211. withBreakpoint
  212. transaction={selectedTransaction}
  213. {...contentCommonProps}
  214. />
  215. ) : (
  216. // queries events-stats for trend data if metrics trend data not found
  217. <EventsRequest
  218. {...requestCommonProps}
  219. organization={organization}
  220. showLoading={false}
  221. includePrevious={false}
  222. yAxis={trendDisplay}
  223. currentSeriesNames={[trendDisplay]}
  224. partial
  225. withoutZerofill={withoutZerofill}
  226. referrer="api.performance.transaction-summary.trends-chart"
  227. >
  228. {({errored, loading, reloading, timeseriesData, timeframe}) => {
  229. return (
  230. <Content
  231. series={timeseriesData}
  232. errored={errored}
  233. loading={loading || isLoading}
  234. reloading={reloading}
  235. timeFrame={timeframe}
  236. withBreakpoint
  237. transaction={selectedTransaction}
  238. {...contentCommonProps}
  239. />
  240. );
  241. }}
  242. </EventsRequest>
  243. );
  244. }}
  245. </TrendsDiscoverQuery>
  246. ) : (
  247. <EventsRequest
  248. {...requestCommonProps}
  249. organization={organization}
  250. showLoading={false}
  251. includePrevious={false}
  252. yAxis={trendDisplay}
  253. currentSeriesNames={[trendDisplay]}
  254. partial
  255. withoutZerofill={withoutZerofill}
  256. referrer="api.performance.transaction-summary.trends-chart"
  257. >
  258. {({errored, loading, reloading, timeseriesData, timeframe: timeFrame}) => {
  259. return (
  260. <Content
  261. series={timeseriesData}
  262. errored={errored}
  263. loading={loading || isCardinalityCheckLoading}
  264. reloading={reloading}
  265. timeFrame={timeFrame}
  266. {...contentCommonProps}
  267. />
  268. );
  269. }}
  270. </EventsRequest>
  271. )}
  272. </Fragment>
  273. );
  274. }
  275. export default TrendChart;