teamStability.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 countSeriesWeeklyTotals: number[] = Array(sumSessions.length / 7).fill(0);
  126. countSeries.forEach(
  127. (s, idx) => (countSeriesWeeklyTotals[Math.floor(idx / 7)] += s.value)
  128. );
  129. const sumSessionsWeeklyTotals: number[] = Array(sumSessions.length / 7).fill(0);
  130. sumSessions.forEach((s, idx) => (sumSessionsWeeklyTotals[Math.floor(idx / 7)] += s));
  131. const data = countSeriesWeeklyTotals.map((value, idx) => ({
  132. name: countSeries[idx * 7].name,
  133. value: sumSessionsWeeklyTotals[idx]
  134. ? formatFloat((value / sumSessionsWeeklyTotals[idx]) * 100, 2)
  135. : 0,
  136. }));
  137. return [{seriesName: t('Crash Free Sessions'), data}];
  138. }
  139. function renderScore(projectId: string, dataset: 'week' | 'period') {
  140. if (isLoading) {
  141. return (
  142. <div>
  143. <Placeholder width="80px" height="25px" />
  144. </div>
  145. );
  146. }
  147. const score = getScore(Number(projectId), dataset);
  148. if (score === null) {
  149. return '\u2014';
  150. }
  151. return displayCrashFreePercent(score);
  152. }
  153. function renderTrend(projectId: string) {
  154. if (isLoading) {
  155. return (
  156. <div>
  157. <Placeholder width="80px" height="25px" />
  158. </div>
  159. );
  160. }
  161. const trend = getTrend(Number(projectId));
  162. if (trend === null) {
  163. return '\u2014';
  164. }
  165. return (
  166. <SubText color={trend >= 0 ? 'successText' : 'errorText'}>
  167. {`${round(Math.abs(trend), 3)}\u0025`}
  168. <PaddedIconArrow direction={trend >= 0 ? 'up' : 'down'} size="xs" />
  169. </SubText>
  170. );
  171. }
  172. const sortedProjects = projects
  173. .map(project => ({project, trend: getTrend(Number(project.id)) ?? 0}))
  174. .sort((a, b) => Math.abs(b.trend) - Math.abs(a.trend));
  175. const groupedProjects = groupByTrend(sortedProjects);
  176. return (
  177. <StyledPanelTable
  178. isEmpty={projects.length === 0}
  179. emptyMessage={t('No projects with release health enabled')}
  180. emptyAction={
  181. <Button
  182. size="sm"
  183. external
  184. href="https://docs.sentry.io/platforms/dotnet/guides/nlog/configuration/releases/#release-health"
  185. >
  186. {t('Learn More')}
  187. </Button>
  188. }
  189. headers={[
  190. t('Project'),
  191. <RightAligned key="last">{tct('Last [period]', {period})}</RightAligned>,
  192. <RightAligned key="avg">{tct('[period] Avg', {period})}</RightAligned>,
  193. <RightAligned key="curr">{t('Last 7 Days')}</RightAligned>,
  194. <RightAligned key="diff">{t('Difference')}</RightAligned>,
  195. ]}
  196. >
  197. {groupedProjects.map(({project}) => (
  198. <Fragment key={project.id}>
  199. <ProjectBadgeContainer>
  200. <ProjectBadge avatarSize={18} project={project} />
  201. </ProjectBadgeContainer>
  202. <div>
  203. {periodSessions && weekSessions && !isLoading && (
  204. <MiniBarChart
  205. isGroupedByDate
  206. showTimeInTooltip
  207. series={getMiniBarChartSeries(project, periodSessions)}
  208. height={25}
  209. tooltipFormatter={(value: number) => `${value.toLocaleString()}%`}
  210. />
  211. )}
  212. </div>
  213. <ScoreWrapper>{renderScore(project.id, 'period')}</ScoreWrapper>
  214. <ScoreWrapper>{renderScore(project.id, 'week')}</ScoreWrapper>
  215. <ScoreWrapper>{renderTrend(project.id)}</ScoreWrapper>
  216. </Fragment>
  217. ))}
  218. </StyledPanelTable>
  219. );
  220. }
  221. export default TeamStability;
  222. const StyledPanelTable = styled(PanelTable)<{isEmpty: boolean}>`
  223. grid-template-columns: 1fr 0.2fr 0.2fr 0.2fr 0.2fr;
  224. font-size: ${p => p.theme.fontSizeMedium};
  225. white-space: nowrap;
  226. margin-bottom: 0;
  227. border: 0;
  228. box-shadow: unset;
  229. /* overflow when bar chart tooltip gets cutoff for the top row */
  230. overflow: visible;
  231. & > div {
  232. padding: ${space(1)} ${space(2)};
  233. }
  234. ${p =>
  235. p.isEmpty &&
  236. css`
  237. & > div:last-child {
  238. padding: 48px ${space(2)};
  239. }
  240. `}
  241. `;
  242. const RightAligned = styled('span')`
  243. text-align: right;
  244. `;
  245. const ScoreWrapper = styled('div')`
  246. display: flex;
  247. align-items: center;
  248. justify-content: flex-end;
  249. text-align: right;
  250. `;
  251. const PaddedIconArrow = styled(IconArrow)`
  252. margin: 0 ${space(0.5)};
  253. `;
  254. const SubText = styled('div')<{color: ColorOrAlias}>`
  255. color: ${p => p.theme[p.color]};
  256. `;