projectSessionsChartRequest.tsx 10 KB

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