index.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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 TrendsDiscoverQuery from 'sentry/utils/performance/trends/trendsDiscoverQuery';
  18. import useApi from 'sentry/utils/useApi';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import useRouter from 'sentry/utils/useRouter';
  21. import {
  22. TrendChangeType,
  23. TrendFunctionField,
  24. TrendView,
  25. } from 'sentry/views/performance/trends/types';
  26. import {
  27. generateTrendFunctionAsString,
  28. modifyTrendView,
  29. normalizeTrends,
  30. } from 'sentry/views/performance/trends/utils';
  31. import {ViewProps} from 'sentry/views/performance/types';
  32. import {getSelectedTransaction} from 'sentry/views/performance/utils';
  33. import Content from './content';
  34. type Props = ViewProps & {
  35. eventView: EventView;
  36. organization: OrganizationSummary;
  37. projects: Project[];
  38. queryExtra: Query;
  39. trendFunction: TrendFunctionField;
  40. trendParameter: string;
  41. withoutZerofill: boolean;
  42. withBreakpoint?: boolean;
  43. };
  44. function TrendChart({
  45. project,
  46. environment,
  47. organization,
  48. query,
  49. statsPeriod,
  50. trendFunction,
  51. trendParameter,
  52. queryExtra,
  53. withoutZerofill,
  54. withBreakpoint,
  55. eventView,
  56. start: propsStart,
  57. end: propsEnd,
  58. projects,
  59. }: Props) {
  60. const router = useRouter();
  61. const location = useLocation();
  62. const api = useApi();
  63. const theme = useTheme();
  64. function handleLegendSelectChanged(legendChange: {
  65. name: string;
  66. selected: Record<string, boolean>;
  67. type: string;
  68. }) {
  69. const {selected} = legendChange;
  70. const unselected = Object.keys(selected).filter(key => !selected[key]);
  71. const to = {
  72. ...location,
  73. query: {
  74. ...location.query,
  75. unselectedSeries: unselected,
  76. },
  77. };
  78. browserHistory.push(to);
  79. }
  80. const start = propsStart ? getUtcToLocalDateObject(propsStart) : null;
  81. const end = propsEnd ? getUtcToLocalDateObject(propsEnd) : null;
  82. const utc = normalizeDateTimeParams(location.query)?.utc === 'true';
  83. const period = statsPeriod;
  84. const legend = {
  85. right: 10,
  86. top: 0,
  87. selected: getSeriesSelection(location),
  88. };
  89. const datetimeSelection = {start, end, period};
  90. const contentCommonProps = {
  91. theme,
  92. router,
  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.REGRESSION,
  129. projects,
  130. organization
  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. {withBreakpoint ? (
  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={withBreakpoint}
  164. >
  165. {({isLoading, trendsData}) => {
  166. const events = normalizeTrends(
  167. (trendsData && trendsData.events && trendsData.events.data) || []
  168. );
  169. // keep trend change type as regression until the backend can support passing the type
  170. const selectedTransaction = getSelectedTransaction(
  171. location,
  172. TrendChangeType.REGRESSION,
  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 && 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}
  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}
  258. reloading={reloading}
  259. timeFrame={timeFrame}
  260. {...contentCommonProps}
  261. />
  262. );
  263. }}
  264. </EventsRequest>
  265. )}
  266. </Fragment>
  267. );
  268. }
  269. export default TrendChart;