eventGraph.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. import {type CSSProperties, useMemo, useState} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import Color from 'color';
  5. import Alert from 'sentry/components/alert';
  6. import {Button, type ButtonProps} from 'sentry/components/button';
  7. import {BarChart, type BarChartSeries} from 'sentry/components/charts/barChart';
  8. import Legend from 'sentry/components/charts/components/legend';
  9. import {defaultFormatAxisLabel} from 'sentry/components/charts/components/tooltip';
  10. import {useChartZoom} from 'sentry/components/charts/useChartZoom';
  11. import {Flex} from 'sentry/components/container/flex';
  12. import InteractionStateLayer from 'sentry/components/interactionStateLayer';
  13. import Placeholder from 'sentry/components/placeholder';
  14. import {t, tct, tn} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import type {SeriesDataUnit} from 'sentry/types/echarts';
  17. import type {Event} from 'sentry/types/event';
  18. import type {Group} from 'sentry/types/group';
  19. import type {EventsStats, MultiSeriesEventsStats} from 'sentry/types/organization';
  20. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  21. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  22. import {getConfigForIssueType} from 'sentry/utils/issueTypeConfig';
  23. import {useApiQuery} from 'sentry/utils/queryClient';
  24. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import {getBucketSize} from 'sentry/views/dashboards/widgetCard/utils';
  28. import useFlagSeries from 'sentry/views/issueDetails/streamline/hooks/useFlagSeries';
  29. import {
  30. useIssueDetailsDiscoverQuery,
  31. useIssueDetailsEventView,
  32. } from 'sentry/views/issueDetails/streamline/hooks/useIssueDetailsDiscoverQuery';
  33. import {useReleaseMarkLineSeries} from 'sentry/views/issueDetails/streamline/hooks/useReleaseMarkLineSeries';
  34. export const enum EventGraphSeries {
  35. EVENT = 'event',
  36. USER = 'user',
  37. }
  38. interface EventGraphProps {
  39. event: Event | undefined;
  40. group: Group;
  41. className?: string;
  42. style?: CSSProperties;
  43. }
  44. function createSeriesAndCount(stats: EventsStats) {
  45. return stats?.data?.reduce(
  46. (result, [timestamp, countData]) => {
  47. const count = countData?.[0]?.count ?? 0;
  48. return {
  49. series: [
  50. ...result.series,
  51. {
  52. name: timestamp * 1000, // ms -> s
  53. value: count,
  54. },
  55. ],
  56. count: result.count + count,
  57. };
  58. },
  59. {series: [] as SeriesDataUnit[], count: 0}
  60. );
  61. }
  62. export function EventGraph({group, event, ...styleProps}: EventGraphProps) {
  63. const theme = useTheme();
  64. const organization = useOrganization();
  65. const location = useLocation();
  66. const [visibleSeries, setVisibleSeries] = useState<EventGraphSeries>(
  67. EventGraphSeries.EVENT
  68. );
  69. const eventView = useIssueDetailsEventView({group});
  70. const hasFeatureFlagFeature = organization.features.includes('feature-flag-ui');
  71. const config = getConfigForIssueType(group, group.project);
  72. const {
  73. data: groupStats = {},
  74. isPending: isLoadingStats,
  75. error,
  76. } = useIssueDetailsDiscoverQuery<MultiSeriesEventsStats>({
  77. params: {
  78. route: 'events-stats',
  79. eventView,
  80. referrer: 'issue_details.streamline_graph',
  81. },
  82. });
  83. const noQueryEventView = eventView.clone();
  84. noQueryEventView.query = `issue:${group.shortId}`;
  85. noQueryEventView.environment = [];
  86. const isUnfilteredStatsEnabled =
  87. eventView.query !== noQueryEventView.query || eventView.environment.length > 0;
  88. const {data: unfilteredGroupStats} =
  89. useIssueDetailsDiscoverQuery<MultiSeriesEventsStats>({
  90. options: {
  91. enabled: isUnfilteredStatsEnabled,
  92. },
  93. params: {
  94. route: 'events-stats',
  95. eventView: noQueryEventView,
  96. referrer: 'issue_details.streamline_graph',
  97. },
  98. });
  99. const {data: uniqueUsersCount, isPending: isPendingUniqueUsersCount} = useApiQuery<{
  100. data: Array<{count_unique: number}>;
  101. }>(
  102. [
  103. `/organizations/${organization.slug}/events/`,
  104. {
  105. query: {
  106. ...eventView.getEventsAPIPayload(location),
  107. dataset: config.usesIssuePlatform
  108. ? DiscoverDatasets.ISSUE_PLATFORM
  109. : DiscoverDatasets.ERRORS,
  110. field: 'count_unique(user)',
  111. per_page: 50,
  112. project: group.project.id,
  113. query: eventView.query,
  114. referrer: 'issue_details.streamline_graph',
  115. },
  116. },
  117. ],
  118. {
  119. staleTime: 60_000,
  120. }
  121. );
  122. const userCount = uniqueUsersCount?.data[0]?.['count_unique(user)'] ?? 0;
  123. const {series: eventSeries, count: eventCount} = useMemo(() => {
  124. if (!groupStats['count()']) {
  125. return {series: [], count: 0};
  126. }
  127. return createSeriesAndCount(groupStats['count()']);
  128. }, [groupStats]);
  129. const {series: unfilteredEventSeries} = useMemo(() => {
  130. if (!unfilteredGroupStats?.['count()']) {
  131. return {series: []};
  132. }
  133. return createSeriesAndCount(unfilteredGroupStats['count()']);
  134. }, [unfilteredGroupStats]);
  135. const {series: unfilteredUserSeries} = useMemo(() => {
  136. if (!unfilteredGroupStats?.['count_unique(user)']) {
  137. return {series: []};
  138. }
  139. return createSeriesAndCount(unfilteredGroupStats['count_unique(user)']);
  140. }, [unfilteredGroupStats]);
  141. const userSeries = useMemo(() => {
  142. if (!groupStats['count_unique(user)']) {
  143. return [];
  144. }
  145. return createSeriesAndCount(groupStats['count_unique(user)']).series;
  146. }, [groupStats]);
  147. const chartZoomProps = useChartZoom({
  148. saveOnZoom: true,
  149. });
  150. const releaseSeries = useReleaseMarkLineSeries({group});
  151. const flagSeries = useFlagSeries({
  152. query: {
  153. start: eventView.start,
  154. end: eventView.end,
  155. statsPeriod: eventView.statsPeriod,
  156. },
  157. event,
  158. });
  159. const series = useMemo((): BarChartSeries[] => {
  160. const seriesData: BarChartSeries[] = [];
  161. const translucentGray300 = Color(theme.gray300).alpha(0.3).string();
  162. if (visibleSeries === EventGraphSeries.USER) {
  163. if (isUnfilteredStatsEnabled) {
  164. seriesData.push({
  165. seriesName: t('Total users'),
  166. itemStyle: {
  167. borderRadius: [2, 2, 0, 0],
  168. borderColor: theme.translucentGray200,
  169. color: translucentGray300,
  170. },
  171. barGap: '-100%', // Makes bars overlap completely
  172. data: unfilteredUserSeries,
  173. animation: false,
  174. });
  175. }
  176. seriesData.push({
  177. seriesName: isUnfilteredStatsEnabled ? t('Matching users') : t('Users'),
  178. itemStyle: {
  179. borderRadius: [2, 2, 0, 0],
  180. borderColor: theme.translucentGray200,
  181. color: theme.purple200,
  182. },
  183. data: userSeries,
  184. animation: false,
  185. });
  186. }
  187. if (visibleSeries === EventGraphSeries.EVENT) {
  188. if (isUnfilteredStatsEnabled) {
  189. seriesData.push({
  190. seriesName: t('Total events'),
  191. itemStyle: {
  192. borderRadius: [2, 2, 0, 0],
  193. borderColor: theme.translucentGray200,
  194. color: translucentGray300,
  195. },
  196. barGap: '-100%', // Makes bars overlap completely
  197. data: unfilteredEventSeries,
  198. animation: false,
  199. });
  200. }
  201. seriesData.push({
  202. seriesName: isUnfilteredStatsEnabled ? t('Matching events') : t('Events'),
  203. itemStyle: {
  204. borderRadius: [2, 2, 0, 0],
  205. borderColor: theme.translucentGray200,
  206. color: isUnfilteredStatsEnabled ? theme.purple200 : translucentGray300,
  207. },
  208. data: eventSeries,
  209. animation: false,
  210. });
  211. }
  212. if (releaseSeries.markLine) {
  213. seriesData.push(releaseSeries as BarChartSeries);
  214. }
  215. if (flagSeries.markLine && hasFeatureFlagFeature) {
  216. seriesData.push(flagSeries as BarChartSeries);
  217. }
  218. return seriesData;
  219. }, [
  220. visibleSeries,
  221. userSeries,
  222. eventSeries,
  223. releaseSeries,
  224. flagSeries,
  225. theme,
  226. hasFeatureFlagFeature,
  227. isUnfilteredStatsEnabled,
  228. unfilteredEventSeries,
  229. unfilteredUserSeries,
  230. ]);
  231. const bucketSize = eventSeries ? getBucketSize(series) : undefined;
  232. const [legendSelected, setLegendSelected] = useLocalStorageState(
  233. 'issue-details-graph-legend',
  234. {
  235. ['Feature Flags']: true,
  236. ['Releases']: false,
  237. }
  238. );
  239. const legend = Legend({
  240. theme: theme,
  241. orient: 'horizontal',
  242. align: 'left',
  243. show: true,
  244. top: 4,
  245. right: 8,
  246. data: hasFeatureFlagFeature ? ['Feature Flags', 'Releases'] : ['Releases'],
  247. selected: legendSelected,
  248. zlevel: 10,
  249. inactiveColor: theme.gray200,
  250. });
  251. const onLegendSelectChanged = useMemo(
  252. () =>
  253. ({name, selected: record}) => {
  254. const newValue = record[name];
  255. setLegendSelected(prevState => ({
  256. ...prevState,
  257. [name]: newValue,
  258. }));
  259. },
  260. [setLegendSelected]
  261. );
  262. if (error) {
  263. return (
  264. <GraphAlert type="error" showIcon {...styleProps}>
  265. {tct('Graph Query Error: [message]', {message: error.message})}
  266. </GraphAlert>
  267. );
  268. }
  269. if (isLoadingStats || isPendingUniqueUsersCount) {
  270. return (
  271. <GraphWrapper {...styleProps}>
  272. <SummaryContainer>
  273. <GraphButton
  274. isActive={visibleSeries === EventGraphSeries.EVENT}
  275. disabled
  276. label={t('Events')}
  277. />
  278. <GraphButton
  279. isActive={visibleSeries === EventGraphSeries.USER}
  280. disabled
  281. label={t('Users')}
  282. />
  283. </SummaryContainer>
  284. <LoadingChartContainer>
  285. <Placeholder height="96px" testId="event-graph-loading" />
  286. </LoadingChartContainer>
  287. </GraphWrapper>
  288. );
  289. }
  290. return (
  291. <GraphWrapper {...styleProps}>
  292. <SummaryContainer>
  293. <GraphButton
  294. onClick={() =>
  295. visibleSeries === EventGraphSeries.USER &&
  296. setVisibleSeries(EventGraphSeries.EVENT)
  297. }
  298. isActive={visibleSeries === EventGraphSeries.EVENT}
  299. disabled={visibleSeries === EventGraphSeries.EVENT}
  300. label={tn('Event', 'Events', eventCount)}
  301. count={String(eventCount)}
  302. />
  303. <GraphButton
  304. onClick={() =>
  305. visibleSeries === EventGraphSeries.EVENT &&
  306. setVisibleSeries(EventGraphSeries.USER)
  307. }
  308. isActive={visibleSeries === EventGraphSeries.USER}
  309. disabled={visibleSeries === EventGraphSeries.USER}
  310. label={tn('User', 'Users', userCount)}
  311. count={String(userCount)}
  312. />
  313. </SummaryContainer>
  314. <ChartContainer role="figure">
  315. <BarChart
  316. height={100}
  317. series={series}
  318. legend={legend}
  319. onLegendSelectChanged={onLegendSelectChanged}
  320. showTimeInTooltip
  321. grid={{
  322. left: 8,
  323. right: 8,
  324. top: 20,
  325. bottom: 0,
  326. }}
  327. tooltip={{
  328. formatAxisLabel: (
  329. value,
  330. isTimestamp,
  331. utc,
  332. showTimeInTooltip,
  333. addSecondsToTimeFormat,
  334. _bucketSize,
  335. _seriesParamsOrParam
  336. ) =>
  337. String(
  338. defaultFormatAxisLabel(
  339. value,
  340. isTimestamp,
  341. utc,
  342. showTimeInTooltip,
  343. addSecondsToTimeFormat,
  344. bucketSize
  345. )
  346. ),
  347. }}
  348. yAxis={{
  349. splitNumber: 2,
  350. minInterval: 1,
  351. axisLabel: {
  352. formatter: (value: number) => {
  353. return formatAbbreviatedNumber(value);
  354. },
  355. },
  356. }}
  357. {...chartZoomProps}
  358. />
  359. </ChartContainer>
  360. </GraphWrapper>
  361. );
  362. }
  363. function GraphButton({
  364. isActive,
  365. label,
  366. count,
  367. ...props
  368. }: {isActive: boolean; label: string; count?: string} & Partial<ButtonProps>) {
  369. return (
  370. <Callout
  371. isActive={isActive}
  372. aria-label={`${t('Toggle graph series')} - ${label}`}
  373. {...props}
  374. >
  375. <InteractionStateLayer hidden={isActive} />
  376. <Flex column>
  377. <Label isActive={isActive}>{label}</Label>
  378. <Count isActive={isActive}>{count ? formatAbbreviatedNumber(count) : '-'}</Count>
  379. </Flex>
  380. </Callout>
  381. );
  382. }
  383. const GraphWrapper = styled('div')`
  384. display: grid;
  385. grid-template-columns: auto 1fr;
  386. `;
  387. const SummaryContainer = styled('div')`
  388. display: flex;
  389. gap: ${space(0.5)};
  390. flex-direction: column;
  391. margin: ${space(1)} ${space(1)} ${space(1)} 0;
  392. border-radius: ${p => p.theme.borderRadiusLeft};
  393. `;
  394. const Callout = styled(Button)<{isActive: boolean}>`
  395. cursor: ${p => (p.isActive ? 'initial' : 'pointer')};
  396. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  397. background: ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  398. padding: ${space(0.5)} ${space(2)};
  399. box-shadow: none;
  400. height: unset;
  401. overflow: hidden;
  402. &:disabled {
  403. opacity: 1;
  404. }
  405. &:hover {
  406. border: 1px solid ${p => (p.isActive ? p.theme.purple100 : 'transparent')};
  407. }
  408. `;
  409. const Label = styled('div')<{isActive: boolean}>`
  410. line-height: 1;
  411. font-size: ${p => p.theme.fontSizeSmall};
  412. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.subText)};
  413. `;
  414. const Count = styled('div')<{isActive: boolean}>`
  415. line-height: 1;
  416. margin-top: ${space(0.5)};
  417. font-size: 20px;
  418. font-weight: ${p => p.theme.fontWeightNormal};
  419. color: ${p => (p.isActive ? p.theme.purple400 : p.theme.textColor)};
  420. `;
  421. const ChartContainer = styled('div')`
  422. position: relative;
  423. padding: ${space(0.75)} ${space(1)} ${space(0.75)} 0;
  424. `;
  425. const LoadingChartContainer = styled('div')`
  426. position: relative;
  427. padding: ${space(1)} ${space(1)};
  428. `;
  429. const GraphAlert = styled(Alert)`
  430. padding-left: 24px;
  431. margin: 0 0 0 -24px;
  432. border: 0;
  433. border-radius: 0;
  434. `;