teamStability.tsx 8.2 KB

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