releasesRequest.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. import {Component} from 'react';
  2. import type {Location} from 'history';
  3. import isEqual from 'lodash/isEqual';
  4. import omit from 'lodash/omit';
  5. import pick from 'lodash/pick';
  6. import moment from 'moment-timezone';
  7. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  8. import type {Client} from 'sentry/api';
  9. import type {DateTimeObject} from 'sentry/components/charts/utils';
  10. import {
  11. getDiffInMinutes,
  12. ONE_WEEK,
  13. TWENTY_FOUR_HOURS,
  14. TWO_WEEKS,
  15. } from 'sentry/components/charts/utils';
  16. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  17. import {URL_PARAM} from 'sentry/constants/pageFilters';
  18. import {t} from 'sentry/locale';
  19. import type {Organization, PageFilters, SessionApiResponse} from 'sentry/types';
  20. import {HealthStatsPeriodOption, SessionFieldWithOperation} from 'sentry/types';
  21. import {defined, percent} from 'sentry/utils';
  22. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  23. import withApi from 'sentry/utils/withApi';
  24. import {getCrashFreePercent} from '../utils';
  25. import {ReleasesDisplayOption} from './releasesDisplayOptions';
  26. function omitIgnoredProps(props: Props) {
  27. return omit(props, [
  28. 'api',
  29. 'organization',
  30. 'children',
  31. 'selection.datetime.utc',
  32. 'location',
  33. ]);
  34. }
  35. function getInterval(datetimeObj: DateTimeObject) {
  36. const diffInMinutes = getDiffInMinutes(datetimeObj);
  37. if (diffInMinutes >= TWO_WEEKS) {
  38. return '1d';
  39. }
  40. if (diffInMinutes >= ONE_WEEK) {
  41. return '6h';
  42. }
  43. if (diffInMinutes > TWENTY_FOUR_HOURS) {
  44. return '4h';
  45. }
  46. // TODO(sessions): sub-hour session resolution is still not possible
  47. return '1h';
  48. }
  49. export function reduceTimeSeriesGroups(
  50. acc: number[],
  51. group: SessionApiResponse['groups'][number],
  52. field: 'count_unique(user)' | 'sum(session)'
  53. ) {
  54. group.series[field]?.forEach(
  55. (value, index) => (acc[index] = (acc[index] ?? 0) + value)
  56. );
  57. return acc;
  58. }
  59. export function sessionDisplayToField(display: ReleasesDisplayOption) {
  60. switch (display) {
  61. case ReleasesDisplayOption.USERS:
  62. return SessionFieldWithOperation.USERS;
  63. case ReleasesDisplayOption.SESSIONS:
  64. default:
  65. return SessionFieldWithOperation.SESSIONS;
  66. }
  67. }
  68. export type ReleasesRequestRenderProps = {
  69. errored: boolean;
  70. getHealthData: ReturnType<ReleasesRequest['getHealthData']>;
  71. isHealthLoading: boolean;
  72. };
  73. type Props = {
  74. api: Client;
  75. children: (renderProps: ReleasesRequestRenderProps) => React.ReactNode;
  76. display: ReleasesDisplayOption[];
  77. location: Location;
  78. organization: Organization;
  79. releases: string[];
  80. selection: PageFilters;
  81. defaultStatsPeriod?: string;
  82. disable?: boolean;
  83. healthStatsPeriod?: HealthStatsPeriodOption;
  84. releasesReloading?: boolean;
  85. };
  86. type State = {
  87. errored: boolean;
  88. loading: boolean;
  89. statusCountByProjectInPeriod: SessionApiResponse | null;
  90. statusCountByReleaseInPeriod: SessionApiResponse | null;
  91. totalCountByProjectIn24h: SessionApiResponse | null;
  92. totalCountByProjectInPeriod: SessionApiResponse | null;
  93. totalCountByReleaseIn24h: SessionApiResponse | null;
  94. totalCountByReleaseInPeriod: SessionApiResponse | null;
  95. };
  96. class ReleasesRequest extends Component<Props, State> {
  97. state: State = {
  98. loading: false,
  99. errored: false,
  100. statusCountByReleaseInPeriod: null,
  101. totalCountByReleaseIn24h: null,
  102. totalCountByProjectIn24h: null,
  103. statusCountByProjectInPeriod: null,
  104. totalCountByReleaseInPeriod: null,
  105. totalCountByProjectInPeriod: null,
  106. };
  107. componentDidMount() {
  108. this.fetchData();
  109. }
  110. componentDidUpdate(prevProps: Props) {
  111. if (this.props.releasesReloading) {
  112. return;
  113. }
  114. if (isEqual(omitIgnoredProps(prevProps), omitIgnoredProps(this.props))) {
  115. return;
  116. }
  117. this.fetchData();
  118. }
  119. get path() {
  120. const {organization} = this.props;
  121. return `/organizations/${organization.slug}/sessions/`;
  122. }
  123. get baseQueryParams() {
  124. const {location, selection, defaultStatsPeriod, releases} = this.props;
  125. return {
  126. query: new MutableSearch(
  127. releases.reduce<string[]>((acc, release, index, allReleases) => {
  128. acc.push(`release:"${release}"`);
  129. if (index < allReleases.length - 1) {
  130. acc.push('OR');
  131. }
  132. return acc;
  133. }, [])
  134. ).formatString(),
  135. interval: getInterval(selection.datetime),
  136. ...normalizeDateTimeParams(pick(location.query, Object.values(URL_PARAM)), {
  137. defaultStatsPeriod,
  138. }),
  139. };
  140. }
  141. fetchData = async () => {
  142. const {api, healthStatsPeriod, disable} = this.props;
  143. if (disable) {
  144. return;
  145. }
  146. api.clear();
  147. this.setState({
  148. loading: true,
  149. errored: false,
  150. statusCountByReleaseInPeriod: null,
  151. totalCountByReleaseIn24h: null,
  152. totalCountByProjectIn24h: null,
  153. });
  154. const promises = [
  155. this.fetchStatusCountByReleaseInPeriod(),
  156. this.fetchTotalCountByReleaseIn24h(),
  157. this.fetchTotalCountByProjectIn24h(),
  158. ];
  159. if (healthStatsPeriod === HealthStatsPeriodOption.AUTO) {
  160. promises.push(this.fetchStatusCountByProjectInPeriod());
  161. promises.push(this.fetchTotalCountByReleaseInPeriod());
  162. promises.push(this.fetchTotalCountByProjectInPeriod());
  163. }
  164. try {
  165. const [
  166. statusCountByReleaseInPeriod,
  167. totalCountByReleaseIn24h,
  168. totalCountByProjectIn24h,
  169. statusCountByProjectInPeriod,
  170. totalCountByReleaseInPeriod,
  171. totalCountByProjectInPeriod,
  172. ] = await Promise.all(promises);
  173. this.setState({
  174. loading: false,
  175. statusCountByReleaseInPeriod,
  176. totalCountByReleaseIn24h,
  177. totalCountByProjectIn24h,
  178. statusCountByProjectInPeriod,
  179. totalCountByReleaseInPeriod,
  180. totalCountByProjectInPeriod,
  181. });
  182. } catch (error) {
  183. addErrorMessage(error.responseJSON?.detail ?? t('Error loading health data'));
  184. this.setState({
  185. loading: false,
  186. errored: true,
  187. });
  188. }
  189. };
  190. /**
  191. * Used to calculate crash free rate, count histogram (This Release series), and crash count
  192. */
  193. async fetchStatusCountByReleaseInPeriod() {
  194. const {api, display} = this.props;
  195. const response: SessionApiResponse = await api.requestPromise(this.path, {
  196. query: {
  197. ...this.baseQueryParams,
  198. field: [
  199. ...new Set([...display.map(d => sessionDisplayToField(d)), 'sum(session)']),
  200. ], // this request needs to be fired for sessions in both display options (because of crash count), removing potential sum(session) duplicated with Set
  201. groupBy: ['project', 'release', 'session.status'],
  202. },
  203. });
  204. return response;
  205. }
  206. /**
  207. * Used to calculate count histogram (Total Project series)
  208. */
  209. async fetchStatusCountByProjectInPeriod() {
  210. const {api, display} = this.props;
  211. const response: SessionApiResponse = await api.requestPromise(this.path, {
  212. query: {
  213. ...this.baseQueryParams,
  214. query: undefined,
  215. field: [
  216. ...new Set([...display.map(d => sessionDisplayToField(d)), 'sum(session)']),
  217. ],
  218. groupBy: ['project', 'session.status'],
  219. },
  220. });
  221. return response;
  222. }
  223. /**
  224. * Used to calculate adoption, and count histogram (This Release series)
  225. */
  226. async fetchTotalCountByReleaseIn24h() {
  227. const {api, display} = this.props;
  228. const response: SessionApiResponse = await api.requestPromise(this.path, {
  229. query: {
  230. ...this.baseQueryParams,
  231. field: display.map(d => sessionDisplayToField(d)),
  232. groupBy: ['project', 'release'],
  233. interval: '1h',
  234. statsPeriod: '24h',
  235. },
  236. });
  237. return response;
  238. }
  239. async fetchTotalCountByReleaseInPeriod() {
  240. const {api, display} = this.props;
  241. const response: SessionApiResponse = await api.requestPromise(this.path, {
  242. query: {
  243. ...this.baseQueryParams,
  244. field: display.map(d => sessionDisplayToField(d)),
  245. groupBy: ['project', 'release'],
  246. },
  247. });
  248. return response;
  249. }
  250. /**
  251. * Used to calculate adoption, and count histogram (Total Project series)
  252. */
  253. async fetchTotalCountByProjectIn24h() {
  254. const {api, display} = this.props;
  255. const response: SessionApiResponse = await api.requestPromise(this.path, {
  256. query: {
  257. ...this.baseQueryParams,
  258. query: undefined,
  259. field: display.map(d => sessionDisplayToField(d)),
  260. groupBy: ['project'],
  261. interval: '1h',
  262. statsPeriod: '24h',
  263. },
  264. });
  265. return response;
  266. }
  267. async fetchTotalCountByProjectInPeriod() {
  268. const {api, display} = this.props;
  269. const response: SessionApiResponse = await api.requestPromise(this.path, {
  270. query: {
  271. ...this.baseQueryParams,
  272. query: undefined,
  273. field: display.map(d => sessionDisplayToField(d)),
  274. groupBy: ['project'],
  275. },
  276. });
  277. return response;
  278. }
  279. getHealthData = () => {
  280. // TODO(sessions): investigate if this needs to be optimized to lower O(n) complexity
  281. return {
  282. getCrashCount: this.getCrashCount,
  283. getCrashFreeRate: this.getCrashFreeRate,
  284. get24hCountByRelease: this.get24hCountByRelease,
  285. get24hCountByProject: this.get24hCountByProject,
  286. getTimeSeries: this.getTimeSeries,
  287. getAdoption: this.getAdoption,
  288. };
  289. };
  290. getCrashCount = (version: string, project: number, display: ReleasesDisplayOption) => {
  291. const {statusCountByReleaseInPeriod} = this.state;
  292. const field = sessionDisplayToField(display);
  293. return statusCountByReleaseInPeriod?.groups.find(
  294. ({by}) =>
  295. by.release === version &&
  296. by.project === project &&
  297. by['session.status'] === 'crashed'
  298. )?.totals[field];
  299. };
  300. getCrashFreeRate = (
  301. version: string,
  302. project: number,
  303. display: ReleasesDisplayOption
  304. ) => {
  305. const {statusCountByReleaseInPeriod} = this.state;
  306. const field = sessionDisplayToField(display);
  307. const totalCount = statusCountByReleaseInPeriod?.groups
  308. .filter(({by}) => by.release === version && by.project === project)
  309. ?.reduce((acc, group) => acc + group.totals[field], 0);
  310. const crashedCount = this.getCrashCount(version, project, display);
  311. return !defined(totalCount) || totalCount === 0
  312. ? null
  313. : getCrashFreePercent(100 - percent(crashedCount ?? 0, totalCount ?? 0));
  314. };
  315. get24hCountByRelease = (
  316. version: string,
  317. project: number,
  318. display: ReleasesDisplayOption
  319. ) => {
  320. const {totalCountByReleaseIn24h} = this.state;
  321. const field = sessionDisplayToField(display);
  322. return totalCountByReleaseIn24h?.groups
  323. .filter(({by}) => by.release === version && by.project === project)
  324. ?.reduce((acc, group) => acc + group.totals[field], 0);
  325. };
  326. getPeriodCountByRelease = (
  327. version: string,
  328. project: number,
  329. display: ReleasesDisplayOption
  330. ) => {
  331. const {totalCountByReleaseInPeriod} = this.state;
  332. const field = sessionDisplayToField(display);
  333. return totalCountByReleaseInPeriod?.groups
  334. .filter(({by}) => by.release === version && by.project === project)
  335. ?.reduce((acc, group) => acc + group.totals[field], 0);
  336. };
  337. get24hCountByProject = (project: number, display: ReleasesDisplayOption) => {
  338. const {totalCountByProjectIn24h} = this.state;
  339. const field = sessionDisplayToField(display);
  340. return totalCountByProjectIn24h?.groups
  341. .filter(({by}) => by.project === project)
  342. ?.reduce((acc, group) => acc + group.totals[field], 0);
  343. };
  344. getPeriodCountByProject = (project: number, display: ReleasesDisplayOption) => {
  345. const {totalCountByProjectInPeriod} = this.state;
  346. const field = sessionDisplayToField(display);
  347. return totalCountByProjectInPeriod?.groups
  348. .filter(({by}) => by.project === project)
  349. ?.reduce((acc, group) => acc + group.totals[field], 0);
  350. };
  351. getTimeSeries = (version: string, project: number, display: ReleasesDisplayOption) => {
  352. const {healthStatsPeriod} = this.props;
  353. if (healthStatsPeriod === HealthStatsPeriodOption.AUTO) {
  354. return this.getPeriodTimeSeries(version, project, display);
  355. }
  356. return this.get24hTimeSeries(version, project, display);
  357. };
  358. get24hTimeSeries = (
  359. version: string,
  360. project: number,
  361. display: ReleasesDisplayOption
  362. ) => {
  363. const {totalCountByReleaseIn24h, totalCountByProjectIn24h} = this.state;
  364. const field = sessionDisplayToField(display);
  365. const intervals = totalCountByProjectIn24h?.intervals ?? [];
  366. const projectData = totalCountByProjectIn24h?.groups.find(
  367. ({by}) => by.project === project
  368. )?.series[field];
  369. const releaseData = totalCountByReleaseIn24h?.groups.find(
  370. ({by}) => by.project === project && by.release === version
  371. )?.series[field];
  372. return [
  373. {
  374. seriesName: t('This Release'),
  375. data: intervals?.map((interval, index) => ({
  376. name: moment(interval).valueOf(),
  377. value: releaseData?.[index] ?? 0,
  378. })),
  379. },
  380. {
  381. seriesName: t('Total Project'),
  382. data: intervals?.map((interval, index) => ({
  383. name: moment(interval).valueOf(),
  384. value: projectData?.[index] ?? 0,
  385. })),
  386. z: 0,
  387. },
  388. ];
  389. };
  390. getPeriodTimeSeries = (
  391. version: string,
  392. project: number,
  393. display: ReleasesDisplayOption
  394. ) => {
  395. const {statusCountByReleaseInPeriod, statusCountByProjectInPeriod} = this.state;
  396. const field = sessionDisplayToField(display);
  397. const intervals = statusCountByProjectInPeriod?.intervals ?? [];
  398. const projectData = statusCountByProjectInPeriod?.groups
  399. .filter(({by}) => by.project === project)
  400. ?.reduce((acc, group) => reduceTimeSeriesGroups(acc, group, field), [] as number[]);
  401. const releaseData = statusCountByReleaseInPeriod?.groups
  402. .filter(({by}) => by.project === project && by.release === version)
  403. ?.reduce((acc, group) => reduceTimeSeriesGroups(acc, group, field), [] as number[]);
  404. return [
  405. {
  406. seriesName: t('This Release'),
  407. data: intervals?.map((interval, index) => ({
  408. name: moment(interval).valueOf(),
  409. value: releaseData?.[index] ?? 0,
  410. })),
  411. },
  412. {
  413. seriesName: t('Total Project'),
  414. data: intervals?.map((interval, index) => ({
  415. name: moment(interval).valueOf(),
  416. value: projectData?.[index] ?? 0,
  417. })),
  418. z: 0,
  419. },
  420. ];
  421. };
  422. getAdoption = (version: string, project: number, display: ReleasesDisplayOption) => {
  423. const {healthStatsPeriod} = this.props;
  424. const countByRelease = (
  425. healthStatsPeriod === HealthStatsPeriodOption.AUTO
  426. ? this.getPeriodCountByRelease
  427. : this.get24hCountByRelease
  428. )(version, project, display);
  429. const countByProject = (
  430. healthStatsPeriod === HealthStatsPeriodOption.AUTO
  431. ? this.getPeriodCountByProject
  432. : this.get24hCountByProject
  433. )(project, display);
  434. return defined(countByRelease) && defined(countByProject)
  435. ? percent(countByRelease, countByProject)
  436. : undefined;
  437. };
  438. render() {
  439. const {loading, errored} = this.state;
  440. const {children} = this.props;
  441. return children({
  442. isHealthLoading: loading,
  443. errored,
  444. getHealthData: this.getHealthData(),
  445. });
  446. }
  447. }
  448. export default withApi(ReleasesRequest);