teamStability.tsx 8.3 KB

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