projectSessionsChartRequest.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. import {Component} from 'react';
  2. import type {Theme} from '@emotion/react';
  3. import {withTheme} from '@emotion/react';
  4. import type {LineSeriesOption} from 'echarts';
  5. import isEqual from 'lodash/isEqual';
  6. import omit from 'lodash/omit';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import type {Client} from 'sentry/api';
  9. import {shouldFetchPreviousPeriod} from 'sentry/components/charts/utils';
  10. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  11. import {t} from 'sentry/locale';
  12. import type {Organization, PageFilters, SessionApiResponse} from 'sentry/types';
  13. import {SessionFieldWithOperation, SessionStatus} from 'sentry/types';
  14. import type {Series} from 'sentry/types/echarts';
  15. import {getPeriod} from 'sentry/utils/getPeriod';
  16. import {
  17. filterSessionsInTimeWindow,
  18. getCount,
  19. getCountSeries,
  20. getSessionsInterval,
  21. initSessionsChart,
  22. } from 'sentry/utils/sessions';
  23. import {getCrashFreePercent} from 'sentry/views/releases/utils';
  24. import {DisplayModes} from '../projectCharts';
  25. const omitIgnoredProps = (props: ProjectSessionsChartRequestProps) =>
  26. omit(props, ['api', 'organization', 'children', 'selection.datetime.utc']);
  27. type ProjectSessionsChartRequestRenderProps = {
  28. errored: boolean;
  29. loading: boolean;
  30. previousTimeseriesData: Series | null;
  31. reloading: boolean;
  32. timeseriesData: Series[];
  33. totalSessions: number | null;
  34. additionalSeries?: LineSeriesOption[];
  35. };
  36. export type ProjectSessionsChartRequestProps = {
  37. api: Client;
  38. children: (renderProps: ProjectSessionsChartRequestRenderProps) => React.ReactNode;
  39. displayMode:
  40. | DisplayModes.SESSIONS
  41. | DisplayModes.STABILITY
  42. | DisplayModes.STABILITY_USERS
  43. // ANR is handled by the ProjectSessionsAnrRequest component
  44. | DisplayModes.ANR_RATE
  45. | DisplayModes.FOREGROUND_ANR_RATE;
  46. onTotalValuesChange: (value: number | null) => void;
  47. organization: Organization;
  48. selection: PageFilters;
  49. theme: Theme;
  50. disablePrevious?: boolean;
  51. query?: string;
  52. };
  53. type State = {
  54. errored: boolean;
  55. previousTimeseriesData: Series | null;
  56. reloading: boolean;
  57. timeseriesData: Series[] | null;
  58. totalSessions: number | null;
  59. };
  60. class ProjectSessionsChartRequest extends Component<
  61. ProjectSessionsChartRequestProps,
  62. State
  63. > {
  64. state: State = {
  65. reloading: false,
  66. errored: false,
  67. timeseriesData: null,
  68. previousTimeseriesData: null,
  69. totalSessions: null,
  70. };
  71. componentDidMount() {
  72. this.fetchData();
  73. }
  74. componentDidUpdate(prevProps: ProjectSessionsChartRequestProps) {
  75. if (!isEqual(omitIgnoredProps(this.props), omitIgnoredProps(prevProps))) {
  76. this.fetchData();
  77. }
  78. }
  79. componentWillUnmount() {
  80. this.unmounting = true;
  81. }
  82. private unmounting: boolean = false;
  83. fetchData = async () => {
  84. const {
  85. api,
  86. selection: {datetime},
  87. onTotalValuesChange,
  88. displayMode,
  89. disablePrevious,
  90. } = this.props;
  91. const shouldFetchWithPrevious =
  92. !disablePrevious &&
  93. shouldFetchPreviousPeriod({
  94. start: datetime.start,
  95. end: datetime.end,
  96. period: datetime.period,
  97. });
  98. this.setState(state => ({
  99. reloading: state.timeseriesData !== null,
  100. errored: false,
  101. }));
  102. try {
  103. const queryParams = this.queryParams({shouldFetchWithPrevious});
  104. const requests = [
  105. api.requestPromise(this.path, {
  106. query: queryParams,
  107. }),
  108. ];
  109. // for crash free sessions and users, we need to make a separate request to get the total count in period
  110. if (this.isCrashFreeRate) {
  111. requests.push(
  112. api.requestPromise(this.path, {
  113. query: {
  114. ...queryParams,
  115. field:
  116. displayMode === DisplayModes.STABILITY_USERS
  117. ? SessionFieldWithOperation.USERS
  118. : SessionFieldWithOperation.SESSIONS,
  119. groupBy: undefined,
  120. ...(shouldFetchWithPrevious ? {statsPeriod: datetime.period} : {}),
  121. },
  122. })
  123. );
  124. }
  125. const [response, totalCountResponse]: SessionApiResponse[] =
  126. await Promise.all(requests);
  127. const filteredResponse = filterSessionsInTimeWindow(
  128. response,
  129. queryParams.start,
  130. queryParams.end
  131. );
  132. const {timeseriesData, previousTimeseriesData, totalCount} =
  133. displayMode === DisplayModes.SESSIONS
  134. ? this.transformSessionCountData(filteredResponse)
  135. : this.transformData(filteredResponse, totalCountResponse, {
  136. fetchedWithPrevious: shouldFetchWithPrevious,
  137. });
  138. if (this.unmounting) {
  139. return;
  140. }
  141. this.setState({
  142. reloading: false,
  143. timeseriesData,
  144. previousTimeseriesData,
  145. totalSessions: totalCount,
  146. });
  147. onTotalValuesChange(totalCount);
  148. } catch {
  149. addErrorMessage(t('Error loading chart data'));
  150. this.setState({
  151. errored: true,
  152. reloading: false,
  153. timeseriesData: null,
  154. previousTimeseriesData: null,
  155. totalSessions: null,
  156. });
  157. }
  158. };
  159. get path() {
  160. const {organization} = this.props;
  161. return `/organizations/${organization.slug}/sessions/`;
  162. }
  163. get field() {
  164. const {displayMode} = this.props;
  165. switch (displayMode) {
  166. case DisplayModes.STABILITY_USERS:
  167. return SessionFieldWithOperation.CRASH_FREE_RATE_USERS;
  168. case DisplayModes.STABILITY:
  169. return SessionFieldWithOperation.CRASH_FREE_RATE_SESSIONS;
  170. default:
  171. return SessionFieldWithOperation.SESSIONS;
  172. }
  173. }
  174. get isCrashFreeRate() {
  175. return [DisplayModes.STABILITY, DisplayModes.STABILITY_USERS].includes(
  176. this.props.displayMode
  177. );
  178. }
  179. queryParams({shouldFetchWithPrevious = false}): Record<string, any> {
  180. const {selection, query, organization} = this.props;
  181. const {datetime, projects, environments: environment} = selection;
  182. const baseParams = {
  183. field: this.field,
  184. groupBy: this.isCrashFreeRate ? undefined : 'session.status',
  185. interval: getSessionsInterval(datetime, {
  186. highFidelity: organization.features.includes('minute-resolution-sessions'),
  187. }),
  188. project: projects[0],
  189. environment,
  190. query,
  191. };
  192. if (!shouldFetchWithPrevious) {
  193. return {
  194. ...baseParams,
  195. ...normalizeDateTimeParams(datetime),
  196. };
  197. }
  198. const {period} = selection.datetime;
  199. const doubledPeriod = getPeriod(
  200. {period, start: undefined, end: undefined},
  201. {shouldDoublePeriod: true}
  202. ).statsPeriod;
  203. return {
  204. ...baseParams,
  205. statsPeriod: doubledPeriod,
  206. };
  207. }
  208. transformData(
  209. responseData: SessionApiResponse,
  210. totalCountResponse: SessionApiResponse,
  211. {fetchedWithPrevious = false}
  212. ) {
  213. const {theme} = this.props;
  214. const {field} = this;
  215. // Take the floor just in case, but data should always be divisible by 2
  216. const dataMiddleIndex = Math.floor(responseData.intervals.length / 2);
  217. // TODO(project-details): refactor this to avoid duplication as we add more session charts
  218. const timeseriesData = [
  219. {
  220. seriesName: t('This Period'),
  221. color: theme.green300,
  222. data: responseData.intervals
  223. .slice(fetchedWithPrevious ? dataMiddleIndex : 0)
  224. .map((interval, i) => {
  225. const crashedSessionsPercent =
  226. responseData.groups[0]?.series[field].slice(
  227. fetchedWithPrevious ? dataMiddleIndex : 0
  228. )[i] * 100 ?? 0;
  229. return {
  230. name: interval,
  231. value: getCrashFreePercent(crashedSessionsPercent),
  232. };
  233. }),
  234. },
  235. ] as Series[]; // TODO(project-detail): Change SeriesDataUnit value to support null
  236. const previousTimeseriesData = fetchedWithPrevious
  237. ? ({
  238. seriesName: t('Previous Period'),
  239. data: responseData.intervals.slice(0, dataMiddleIndex).map((_interval, i) => {
  240. const crashedSessionsPercent =
  241. responseData.groups[0]?.series[field].slice(0, dataMiddleIndex)[i] * 100 ??
  242. 0;
  243. return {
  244. name: responseData.intervals[i + dataMiddleIndex],
  245. value: getCrashFreePercent(crashedSessionsPercent),
  246. };
  247. }),
  248. } as Series) // TODO(project-detail): Change SeriesDataUnit value to support null
  249. : null;
  250. const totalCount =
  251. totalCountResponse?.groups[0].totals[
  252. this.props.displayMode === DisplayModes.STABILITY_USERS
  253. ? SessionFieldWithOperation.USERS
  254. : SessionFieldWithOperation.SESSIONS
  255. ];
  256. return {
  257. timeseriesData,
  258. totalCount,
  259. previousTimeseriesData,
  260. };
  261. }
  262. transformSessionCountData(responseData: SessionApiResponse) {
  263. const {theme} = this.props;
  264. const sessionsChart = initSessionsChart(theme);
  265. const {intervals, groups} = responseData;
  266. const totalSessions = getCount(
  267. responseData.groups,
  268. SessionFieldWithOperation.SESSIONS
  269. );
  270. const chartData = [
  271. {
  272. ...sessionsChart[SessionStatus.HEALTHY],
  273. data: getCountSeries(
  274. SessionFieldWithOperation.SESSIONS,
  275. groups.find(g => g.by['session.status'] === SessionStatus.HEALTHY),
  276. intervals
  277. ),
  278. },
  279. {
  280. ...sessionsChart[SessionStatus.ERRORED],
  281. data: getCountSeries(
  282. SessionFieldWithOperation.SESSIONS,
  283. groups.find(g => g.by['session.status'] === SessionStatus.ERRORED),
  284. intervals
  285. ),
  286. },
  287. {
  288. ...sessionsChart[SessionStatus.ABNORMAL],
  289. data: getCountSeries(
  290. SessionFieldWithOperation.SESSIONS,
  291. groups.find(g => g.by['session.status'] === SessionStatus.ABNORMAL),
  292. intervals
  293. ),
  294. },
  295. {
  296. ...sessionsChart[SessionStatus.CRASHED],
  297. data: getCountSeries(
  298. SessionFieldWithOperation.SESSIONS,
  299. groups.find(g => g.by['session.status'] === SessionStatus.CRASHED),
  300. intervals
  301. ),
  302. },
  303. ];
  304. return {
  305. timeseriesData: chartData,
  306. previousTimeseriesData: null,
  307. totalCount: totalSessions,
  308. };
  309. }
  310. render() {
  311. const {children} = this.props;
  312. const {timeseriesData, reloading, errored, totalSessions, previousTimeseriesData} =
  313. this.state;
  314. const loading = timeseriesData === null;
  315. return children({
  316. loading,
  317. reloading,
  318. errored,
  319. totalSessions,
  320. previousTimeseriesData,
  321. timeseriesData: timeseriesData ?? [],
  322. });
  323. }
  324. }
  325. export default withTheme(ProjectSessionsChartRequest);