teamStability.tsx 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import {Fragment} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import round from 'lodash/round';
  5. import {LinkButton} from 'sentry/components/button';
  6. import MiniBarChart from 'sentry/components/charts/miniBarChart';
  7. import type {DateTimeObject} from 'sentry/components/charts/utils';
  8. import LoadingError from 'sentry/components/loadingError';
  9. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  10. import {PanelTable} from 'sentry/components/panels/panelTable';
  11. import Placeholder from 'sentry/components/placeholder';
  12. import {IconArrow} from 'sentry/icons';
  13. import {t, tct} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import type {Organization, Project, SessionApiResponse} from 'sentry/types';
  16. import {SessionFieldWithOperation, SessionStatus} from 'sentry/types';
  17. import {formatFloat} from 'sentry/utils/number/formatFloat';
  18. import {useApiQuery} from 'sentry/utils/queryClient';
  19. import {getCountSeries, getCrashFreeRate, getSeriesSum} from 'sentry/utils/sessions';
  20. import type {ColorOrAlias} from 'sentry/utils/theme';
  21. import {displayCrashFreePercent} from 'sentry/views/releases/utils';
  22. import {ProjectBadge, ProjectBadgeContainer} from './styles';
  23. import {groupByTrend} from './utils';
  24. interface TeamStabilityProps extends DateTimeObject {
  25. organization: Organization;
  26. projects: Project[];
  27. }
  28. function TeamStability({
  29. organization,
  30. projects,
  31. period,
  32. start,
  33. end,
  34. utc,
  35. }: TeamStabilityProps) {
  36. const projectsWithSessions = projects.filter(project => project.hasSessions);
  37. const datetime = {start, end, period, utc};
  38. const commonQuery = {
  39. environment: [],
  40. project: projectsWithSessions.map(p => p.id),
  41. field: 'sum(session)',
  42. groupBy: ['session.status', 'project'],
  43. interval: '1d',
  44. };
  45. const {
  46. data: periodSessions,
  47. isLoading: isPeriodSessionsLoading,
  48. isError: isPeriodSessionsError,
  49. refetch: refetchPeriodSessions,
  50. } = useApiQuery<SessionApiResponse>(
  51. [
  52. `/organizations/${organization.slug}/sessions/`,
  53. {
  54. query: {
  55. ...commonQuery,
  56. ...normalizeDateTimeParams(datetime),
  57. },
  58. },
  59. ],
  60. {staleTime: 5000}
  61. );
  62. const {
  63. data: weekSessions,
  64. isLoading: isWeekSessionsLoading,
  65. isError: isWeekSessionsError,
  66. refetch: refetchWeekSessions,
  67. } = useApiQuery<SessionApiResponse>(
  68. [
  69. `/organizations/${organization.slug}/sessions/`,
  70. {
  71. query: {
  72. ...commonQuery,
  73. statsPeriod: '7d',
  74. },
  75. },
  76. ],
  77. {staleTime: 5000}
  78. );
  79. const isLoading = isPeriodSessionsLoading || isWeekSessionsLoading;
  80. if (isPeriodSessionsError || isWeekSessionsError) {
  81. return (
  82. <LoadingError
  83. onRetry={() => {
  84. refetchPeriodSessions();
  85. refetchWeekSessions();
  86. }}
  87. />
  88. );
  89. }
  90. function getScore(projectId: number, dataset: 'week' | 'period'): number | null {
  91. const sessions = dataset === 'week' ? weekSessions : periodSessions;
  92. const projectGroups = sessions?.groups.filter(
  93. group => group.by.project === projectId
  94. );
  95. return getCrashFreeRate(projectGroups, SessionFieldWithOperation.SESSIONS);
  96. }
  97. function getTrend(projectId: number): number | null {
  98. const periodScore = getScore(projectId, 'period');
  99. const weekScore = getScore(projectId, 'week');
  100. if (periodScore === null || weekScore === null) {
  101. return null;
  102. }
  103. return weekScore - periodScore;
  104. }
  105. function getMiniBarChartSeries(project: Project, response: SessionApiResponse) {
  106. const sumSessions = getSeriesSum(
  107. response.groups.filter(group => group.by.project === Number(project.id)),
  108. SessionFieldWithOperation.SESSIONS,
  109. response.intervals
  110. );
  111. const countSeries = getCountSeries(
  112. SessionFieldWithOperation.SESSIONS,
  113. response.groups.find(
  114. g =>
  115. g.by.project === Number(project.id) &&
  116. g.by['session.status'] === SessionStatus.HEALTHY
  117. ),
  118. response.intervals
  119. );
  120. const sumSessionsCount = Math.floor(sumSessions.length / 7);
  121. const countSeriesWeeklyTotals: number[] = new Array(sumSessionsCount).fill(0);
  122. countSeries.forEach(
  123. (s, idx) => (countSeriesWeeklyTotals[Math.floor(idx / 7)] += s.value)
  124. );
  125. const sumSessionsWeeklyTotals: number[] = new Array(sumSessionsCount).fill(0);
  126. sumSessions.forEach((s, idx) => (sumSessionsWeeklyTotals[Math.floor(idx / 7)] += s));
  127. const data = countSeriesWeeklyTotals.map((value, idx) => ({
  128. name: countSeries[idx * 7].name,
  129. value: sumSessionsWeeklyTotals[idx]
  130. ? formatFloat((value / sumSessionsWeeklyTotals[idx]) * 100, 2)
  131. : 0,
  132. }));
  133. return [{seriesName: t('Crash Free Sessions'), data}];
  134. }
  135. function renderScore(projectId: string, dataset: 'week' | 'period') {
  136. if (isLoading) {
  137. return (
  138. <div>
  139. <Placeholder width="80px" height="25px" />
  140. </div>
  141. );
  142. }
  143. const score = getScore(Number(projectId), dataset);
  144. if (score === null) {
  145. return '\u2014';
  146. }
  147. return displayCrashFreePercent(score);
  148. }
  149. function renderTrend(projectId: string) {
  150. if (isLoading) {
  151. return (
  152. <div>
  153. <Placeholder width="80px" height="25px" />
  154. </div>
  155. );
  156. }
  157. const trend = getTrend(Number(projectId));
  158. if (trend === null) {
  159. return '\u2014';
  160. }
  161. return (
  162. <SubText color={trend >= 0 ? 'successText' : 'errorText'}>
  163. {`${round(Math.abs(trend), 3)}\u0025`}
  164. <PaddedIconArrow direction={trend >= 0 ? 'up' : 'down'} size="xs" />
  165. </SubText>
  166. );
  167. }
  168. const sortedProjects = projects
  169. .map(project => ({project, trend: getTrend(Number(project.id)) ?? 0}))
  170. .sort((a, b) => Math.abs(b.trend) - Math.abs(a.trend));
  171. const groupedProjects = groupByTrend(sortedProjects);
  172. return (
  173. <StyledPanelTable
  174. isEmpty={projects.length === 0}
  175. emptyMessage={t('No projects with release health enabled')}
  176. emptyAction={
  177. <LinkButton
  178. size="sm"
  179. external
  180. href="https://docs.sentry.io/platforms/dotnet/guides/nlog/configuration/releases/#release-health"
  181. >
  182. {t('Learn More')}
  183. </LinkButton>
  184. }
  185. headers={[
  186. t('Project'),
  187. <RightAligned key="last">{tct('Last [period]', {period})}</RightAligned>,
  188. <RightAligned key="avg">{tct('[period] Avg', {period})}</RightAligned>,
  189. <RightAligned key="curr">{t('Last 7 Days')}</RightAligned>,
  190. <RightAligned key="diff">{t('Difference')}</RightAligned>,
  191. ]}
  192. >
  193. {groupedProjects.map(({project}) => (
  194. <Fragment key={project.id}>
  195. <ProjectBadgeContainer>
  196. <ProjectBadge avatarSize={18} project={project} />
  197. </ProjectBadgeContainer>
  198. <div>
  199. {periodSessions && weekSessions && !isLoading && (
  200. <MiniBarChart
  201. isGroupedByDate
  202. showTimeInTooltip
  203. series={getMiniBarChartSeries(project, periodSessions)}
  204. height={25}
  205. tooltipFormatter={(value: number) => `${value.toLocaleString()}%`}
  206. />
  207. )}
  208. </div>
  209. <ScoreWrapper>{renderScore(project.id, 'period')}</ScoreWrapper>
  210. <ScoreWrapper>{renderScore(project.id, 'week')}</ScoreWrapper>
  211. <ScoreWrapper>{renderTrend(project.id)}</ScoreWrapper>
  212. </Fragment>
  213. ))}
  214. </StyledPanelTable>
  215. );
  216. }
  217. export default TeamStability;
  218. const StyledPanelTable = styled(PanelTable)<{isEmpty: boolean}>`
  219. grid-template-columns: 1fr 0.2fr 0.2fr 0.2fr 0.2fr;
  220. font-size: ${p => p.theme.fontSizeMedium};
  221. white-space: nowrap;
  222. margin-bottom: 0;
  223. border: 0;
  224. box-shadow: unset;
  225. /* overflow when bar chart tooltip gets cutoff for the top row */
  226. overflow: visible;
  227. & > div {
  228. padding: ${space(1)} ${space(2)};
  229. }
  230. ${p =>
  231. p.isEmpty &&
  232. css`
  233. & > div:last-child {
  234. padding: 48px ${space(2)};
  235. }
  236. `}
  237. `;
  238. const RightAligned = styled('span')`
  239. text-align: right;
  240. `;
  241. const ScoreWrapper = styled('div')`
  242. display: flex;
  243. align-items: center;
  244. justify-content: flex-end;
  245. text-align: right;
  246. `;
  247. const PaddedIconArrow = styled(IconArrow)`
  248. margin: 0 ${space(0.5)};
  249. `;
  250. const SubText = styled('div')<{color: ColorOrAlias}>`
  251. color: ${p => p.theme[p.color]};
  252. `;