projectStabilityScoreCard.tsx 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import round from 'lodash/round';
  2. import {
  3. getDiffInMinutes,
  4. shouldFetchPreviousPeriod,
  5. } from 'sentry/components/charts/utils';
  6. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  7. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  8. import ScoreCard from 'sentry/components/scoreCard';
  9. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  10. import {IconArrow} from 'sentry/icons';
  11. import {t} from 'sentry/locale';
  12. import {
  13. Organization,
  14. PageFilters,
  15. SessionApiResponse,
  16. SessionFieldWithOperation,
  17. } from 'sentry/types';
  18. import {defined, percent} from 'sentry/utils';
  19. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  20. import {getPeriod} from 'sentry/utils/getPeriod';
  21. import {displayCrashFreePercent, getCrashFreePercent} from 'sentry/views/releases/utils';
  22. import {
  23. getSessionTermDescription,
  24. SessionTerm,
  25. } from 'sentry/views/releases/utils/sessionTerm';
  26. import MissingReleasesButtons from '../missingFeatureButtons/missingReleasesButtons';
  27. type Props = DeprecatedAsyncComponent['props'] & {
  28. field: SessionFieldWithOperation.SESSIONS | SessionFieldWithOperation.USERS;
  29. hasSessions: boolean | null;
  30. isProjectStabilized: boolean;
  31. organization: Organization;
  32. selection: PageFilters;
  33. query?: string;
  34. };
  35. type State = DeprecatedAsyncComponent['state'] & {
  36. currentSessions: SessionApiResponse | null;
  37. previousSessions: SessionApiResponse | null;
  38. };
  39. class ProjectStabilityScoreCard extends DeprecatedAsyncComponent<Props, State> {
  40. shouldRenderBadRequests = true;
  41. getDefaultState() {
  42. return {
  43. ...super.getDefaultState(),
  44. currentSessions: null,
  45. previousSessions: null,
  46. };
  47. }
  48. getEndpoints() {
  49. const {organization, selection, isProjectStabilized, hasSessions, query, field} =
  50. this.props;
  51. if (!isProjectStabilized || !hasSessions) {
  52. return [];
  53. }
  54. const {projects, environments: environment, datetime} = selection;
  55. const {period} = datetime;
  56. const commonQuery = {
  57. environment,
  58. project: projects[0],
  59. groupBy: 'session.status',
  60. interval: getDiffInMinutes(datetime) > 24 * 60 ? '1d' : '1h',
  61. query,
  62. field,
  63. };
  64. // Unfortunately we can't do something like statsPeriod=28d&interval=14d to get scores for this and previous interval with the single request
  65. // https://github.com/getsentry/sentry/pull/22770#issuecomment-758595553
  66. const endpoints: ReturnType<DeprecatedAsyncComponent['getEndpoints']> = [
  67. [
  68. 'currentSessions',
  69. `/organizations/${organization.slug}/sessions/`,
  70. {
  71. query: {
  72. ...commonQuery,
  73. ...normalizeDateTimeParams(datetime),
  74. },
  75. },
  76. ],
  77. ];
  78. if (
  79. shouldFetchPreviousPeriod({
  80. start: datetime.start,
  81. end: datetime.end,
  82. period: datetime.period,
  83. })
  84. ) {
  85. const doubledPeriod = getPeriod(
  86. {period, start: undefined, end: undefined},
  87. {shouldDoublePeriod: true}
  88. ).statsPeriod;
  89. endpoints.push([
  90. 'previousSessions',
  91. `/organizations/${organization.slug}/sessions/`,
  92. {
  93. query: {
  94. ...commonQuery,
  95. statsPeriodStart: doubledPeriod,
  96. statsPeriodEnd: period ?? DEFAULT_STATS_PERIOD,
  97. },
  98. },
  99. ]);
  100. }
  101. return endpoints;
  102. }
  103. get cardTitle() {
  104. return this.props.field === SessionFieldWithOperation.SESSIONS
  105. ? t('Crash Free Sessions')
  106. : t('Crash Free Users');
  107. }
  108. get cardHelp() {
  109. return getSessionTermDescription(
  110. this.props.field === SessionFieldWithOperation.SESSIONS
  111. ? SessionTerm.CRASH_FREE_SESSIONS
  112. : SessionTerm.CRASH_FREE_USERS,
  113. null
  114. );
  115. }
  116. get score() {
  117. const {currentSessions} = this.state;
  118. return this.calculateCrashFree(currentSessions);
  119. }
  120. get trend() {
  121. const {previousSessions} = this.state;
  122. const previousScore = this.calculateCrashFree(previousSessions);
  123. if (!defined(this.score) || !defined(previousScore)) {
  124. return undefined;
  125. }
  126. return round(this.score - previousScore, 3);
  127. }
  128. get trendStatus(): React.ComponentProps<typeof ScoreCard>['trendStatus'] {
  129. if (!this.trend) {
  130. return undefined;
  131. }
  132. return this.trend > 0 ? 'good' : 'bad';
  133. }
  134. componentDidUpdate(prevProps: Props) {
  135. const {selection, isProjectStabilized, hasSessions, query} = this.props;
  136. if (
  137. prevProps.selection !== selection ||
  138. prevProps.hasSessions !== hasSessions ||
  139. prevProps.isProjectStabilized !== isProjectStabilized ||
  140. prevProps.query !== query
  141. ) {
  142. this.remountComponent();
  143. }
  144. }
  145. calculateCrashFree(data?: SessionApiResponse | null) {
  146. const {field} = this.props;
  147. if (!data) {
  148. return undefined;
  149. }
  150. const totalSessions = data.groups.reduce(
  151. (acc, group) => acc + group.totals[field],
  152. 0
  153. );
  154. const crashedSessions = data.groups.find(
  155. group => group.by['session.status'] === 'crashed'
  156. )?.totals[field];
  157. if (totalSessions === 0 || !defined(totalSessions) || !defined(crashedSessions)) {
  158. return undefined;
  159. }
  160. const crashedSessionsPercent = percent(crashedSessions, totalSessions);
  161. return getCrashFreePercent(100 - crashedSessionsPercent);
  162. }
  163. renderLoading() {
  164. return this.renderBody();
  165. }
  166. renderMissingFeatureCard() {
  167. const {organization} = this.props;
  168. return (
  169. <ScoreCard
  170. title={this.cardTitle}
  171. help={this.cardHelp}
  172. score={<MissingReleasesButtons organization={organization} health />}
  173. />
  174. );
  175. }
  176. renderScore() {
  177. const {loading} = this.state;
  178. if (loading || !defined(this.score)) {
  179. return '\u2014';
  180. }
  181. return displayCrashFreePercent(this.score);
  182. }
  183. renderTrend() {
  184. const {loading} = this.state;
  185. if (loading || !defined(this.score) || !defined(this.trend)) {
  186. return null;
  187. }
  188. return (
  189. <div>
  190. {this.trend >= 0 ? (
  191. <IconArrow direction="up" size="xs" />
  192. ) : (
  193. <IconArrow direction="down" size="xs" />
  194. )}
  195. {`${formatAbbreviatedNumber(Math.abs(this.trend))}\u0025`}
  196. </div>
  197. );
  198. }
  199. renderBody() {
  200. const {hasSessions} = this.props;
  201. if (hasSessions === false) {
  202. return this.renderMissingFeatureCard();
  203. }
  204. return (
  205. <ScoreCard
  206. title={this.cardTitle}
  207. help={this.cardHelp}
  208. score={this.renderScore()}
  209. trend={this.renderTrend()}
  210. trendStatus={this.trendStatus}
  211. />
  212. );
  213. }
  214. }
  215. export default ProjectStabilityScoreCard;