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 {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 {EventsStats, EventsStatsData, OrganizationSummary, Project} from 'sentry/types';
  12. import {Series} from 'sentry/types/echarts';
  13. import {getUtcToLocalDateObject} from 'sentry/utils/dates';
  14. import EventView from 'sentry/utils/discover/eventView';
  15. import {DURATION_UNITS, SIZE_UNITS} from 'sentry/utils/discover/fieldRenderers';
  16. import {getAggregateAlias} from 'sentry/utils/discover/fields';
  17. import {useMetricsCardinalityContext} from 'sentry/utils/performance/contexts/metricsCardinality';
  18. import TrendsDiscoverQuery from 'sentry/utils/performance/trends/trendsDiscoverQuery';
  19. import useApi from 'sentry/utils/useApi';
  20. import {useLocation} from 'sentry/utils/useLocation';
  21. import useRouter from 'sentry/utils/useRouter';
  22. import {
  23. TrendChangeType,
  24. TrendFunctionField,
  25. TrendView,
  26. } from 'sentry/views/performance/trends/types';
  27. import {
  28. generateTrendFunctionAsString,
  29. modifyTrendView,
  30. normalizeTrends,
  31. } from 'sentry/views/performance/trends/utils';
  32. import {ViewProps} from 'sentry/views/performance/types';
  33. import {getSelectedTransaction} from 'sentry/views/performance/utils';
  34. import Content from './content';
  35. type Props = ViewProps & {
  36. eventView: EventView;
  37. organization: OrganizationSummary;
  38. projects: Project[];
  39. queryExtra: Query;
  40. trendFunction: TrendFunctionField;
  41. trendParameter: string;
  42. withoutZerofill: boolean;
  43. withBreakpoint?: boolean;
  44. };
  45. function TrendChart({
  46. project,
  47. environment,
  48. organization,
  49. query,
  50. statsPeriod,
  51. trendFunction,
  52. trendParameter,
  53. queryExtra,
  54. withoutZerofill,
  55. withBreakpoint,
  56. eventView,
  57. start: propsStart,
  58. end: propsEnd,
  59. projects,
  60. }: Props) {
  61. const router = useRouter();
  62. const location = useLocation();
  63. const api = useApi();
  64. const theme = useTheme();
  65. const {isLoading: isCardinalityCheckLoading, outcome} = useMetricsCardinalityContext();
  66. const shouldGetBreakpoint =
  67. withBreakpoint && !isCardinalityCheckLoading && !outcome?.forceTransactionsOnly;
  68. function handleLegendSelectChanged(legendChange: {
  69. name: string;
  70. selected: Record<string, boolean>;
  71. type: string;
  72. }) {
  73. const {selected} = legendChange;
  74. const unselected = Object.keys(selected).filter(key => !selected[key]);
  75. const to = {
  76. ...location,
  77. query: {
  78. ...location.query,
  79. unselectedSeries: unselected,
  80. },
  81. };
  82. browserHistory.push(to);
  83. }
  84. const start = propsStart ? getUtcToLocalDateObject(propsStart) : null;
  85. const end = propsEnd ? getUtcToLocalDateObject(propsEnd) : null;
  86. const utc = normalizeDateTimeParams(location.query)?.utc === 'true';
  87. const period = statsPeriod;
  88. const legend = {
  89. right: 10,
  90. top: 0,
  91. selected: getSeriesSelection(location),
  92. };
  93. const datetimeSelection = {start, end, period};
  94. const contentCommonProps = {
  95. theme,
  96. router,
  97. start,
  98. end,
  99. utc,
  100. legend,
  101. queryExtra,
  102. period,
  103. projects: project,
  104. environments: environment,
  105. onLegendSelectChanged: handleLegendSelectChanged,
  106. };
  107. const requestCommonProps = {
  108. api,
  109. start,
  110. end,
  111. project,
  112. environment,
  113. query,
  114. period,
  115. interval: getInterval(datetimeSelection, 'high'),
  116. };
  117. const header = (
  118. <HeaderTitleLegend>
  119. {t('Trend')}
  120. <QuestionTooltip
  121. size="sm"
  122. position="top"
  123. title={t('Trends shows the smoothed value of an aggregate over time.')}
  124. />
  125. </HeaderTitleLegend>
  126. );
  127. const trendDisplay = generateTrendFunctionAsString(trendFunction, trendParameter);
  128. const trendView = eventView.clone() as TrendView;
  129. modifyTrendView(
  130. trendView,
  131. location,
  132. TrendChangeType.ANY,
  133. projects,
  134. shouldGetBreakpoint
  135. );
  136. function transformTimeseriesData(
  137. data: EventsStatsData,
  138. meta: EventsStats['meta'],
  139. seriesName: string
  140. ): Series[] {
  141. let scale = 1;
  142. if (seriesName) {
  143. const unit = meta?.units?.[getAggregateAlias(seriesName)];
  144. // Scale series values to milliseconds or bytes depending on units from meta
  145. scale = (unit && (DURATION_UNITS[unit] ?? SIZE_UNITS[unit])) ?? 1;
  146. }
  147. return [
  148. {
  149. seriesName,
  150. data: data.map(([timestamp, countsForTimestamp]) => ({
  151. name: timestamp * 1000,
  152. value: countsForTimestamp.reduce((acc, {count}) => acc + count, 0) * scale,
  153. })),
  154. },
  155. ];
  156. }
  157. return (
  158. <Fragment>
  159. {header}
  160. {shouldGetBreakpoint ? (
  161. // queries events-trends-statsv2 for breakpoint data (feature flag only)
  162. <TrendsDiscoverQuery
  163. eventView={trendView}
  164. orgSlug={organization.slug}
  165. location={location}
  166. limit={1}
  167. withBreakpoint
  168. >
  169. {({isLoading, trendsData}) => {
  170. const events = normalizeTrends(
  171. (trendsData && trendsData.events && trendsData.events.data) || []
  172. );
  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 && 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;