releasesRequest.tsx 15 KB

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