usageStatsOrg.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  1. import type {MouseEvent as ReactMouseEvent} from 'react';
  2. import {Fragment} from 'react';
  3. import type {WithRouterProps} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import isEqual from 'lodash/isEqual';
  6. import moment from 'moment-timezone';
  7. import {navigateTo} from 'sentry/actionCreators/navigation';
  8. import type {TooltipSubLabel} from 'sentry/components/charts/components/tooltip';
  9. import OptionSelector from 'sentry/components/charts/optionSelector';
  10. import {InlineContainer, SectionHeading} from 'sentry/components/charts/styles';
  11. import type {DateTimeObject} from 'sentry/components/charts/utils';
  12. import {getSeriesApiInterval} from 'sentry/components/charts/utils';
  13. import {Flex} from 'sentry/components/container/flex';
  14. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  15. import ErrorBoundary from 'sentry/components/errorBoundary';
  16. import NotAvailable from 'sentry/components/notAvailable';
  17. import type {ScoreCardProps} from 'sentry/components/scoreCard';
  18. import ScoreCard from 'sentry/components/scoreCard';
  19. import SwitchButton from 'sentry/components/switchButton';
  20. import {DEFAULT_STATS_PERIOD} from 'sentry/constants';
  21. import {t, tct} from 'sentry/locale';
  22. import {space} from 'sentry/styles/space';
  23. import type {DataCategoryInfo, IntervalPeriod} from 'sentry/types/core';
  24. import type {Organization} from 'sentry/types/organization';
  25. import {parsePeriodToHours} from 'sentry/utils/duration/parsePeriodToHours';
  26. import {FORMAT_DATETIME_DAILY, FORMAT_DATETIME_HOURLY} from './usageChart/utils';
  27. import {mapSeriesToChart} from './mapSeriesToChart';
  28. import type {UsageSeries} from './types';
  29. import type {ChartStats, UsageChartProps} from './usageChart';
  30. import UsageChart, {
  31. CHART_OPTIONS_DATA_TRANSFORM,
  32. ChartDataTransform,
  33. SeriesTypes,
  34. } from './usageChart';
  35. import UsageStatsPerMin from './usageStatsPerMin';
  36. import {isDisplayUtc} from './utils';
  37. export interface UsageStatsOrganizationProps extends WithRouterProps {
  38. dataCategory: DataCategoryInfo['plural'];
  39. dataCategoryApiName: DataCategoryInfo['apiName'];
  40. dataCategoryName: string;
  41. dataDatetime: DateTimeObject;
  42. handleChangeState: (state: {
  43. clientDiscard?: boolean;
  44. dataCategory?: DataCategoryInfo['plural'];
  45. pagePeriod?: string | null;
  46. transform?: ChartDataTransform;
  47. }) => void;
  48. isSingleProject: boolean;
  49. organization: Organization;
  50. projectIds: number[];
  51. chartTransform?: string;
  52. clientDiscard?: boolean;
  53. }
  54. type UsageStatsOrganizationState = {
  55. orgStats: UsageSeries | undefined;
  56. metricOrgStats?: UsageSeries | undefined;
  57. } & DeprecatedAsyncComponent['state'];
  58. /**
  59. * This component is replaced by EnhancedUsageStatsOrganization in getsentry, which inherits
  60. * heavily from this one. Take care if changing any existing function signatures to ensure backwards
  61. * compatibility.
  62. */
  63. class UsageStatsOrganization<
  64. P extends UsageStatsOrganizationProps = UsageStatsOrganizationProps,
  65. S extends UsageStatsOrganizationState = UsageStatsOrganizationState,
  66. > extends DeprecatedAsyncComponent<P, S> {
  67. componentDidUpdate(prevProps: UsageStatsOrganizationProps) {
  68. const {
  69. dataDatetime: prevDateTime,
  70. projectIds: prevProjectIds,
  71. dataCategoryApiName: prevDataCategoryApiName,
  72. } = prevProps;
  73. const {
  74. dataDatetime: currDateTime,
  75. projectIds: currProjectIds,
  76. dataCategoryApiName: currentDataCategoryApiName,
  77. } = this.props;
  78. if (
  79. prevDateTime.start !== currDateTime.start ||
  80. prevDateTime.end !== currDateTime.end ||
  81. prevDateTime.period !== currDateTime.period ||
  82. prevDateTime.utc !== currDateTime.utc ||
  83. prevDataCategoryApiName !== currentDataCategoryApiName ||
  84. !isEqual(prevProjectIds, currProjectIds)
  85. ) {
  86. this.reloadData();
  87. }
  88. }
  89. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  90. return [['orgStats', this.endpointPath, {query: this.endpointQuery}]];
  91. }
  92. /** List of components to render on single-project view */
  93. get projectDetails(): JSX.Element[] {
  94. return [];
  95. }
  96. get endpointPath() {
  97. const {organization} = this.props;
  98. return `/organizations/${organization.slug}/stats_v2/`;
  99. }
  100. get endpointQueryDatetime() {
  101. const {dataDatetime} = this.props;
  102. const queryDatetime =
  103. dataDatetime.start && dataDatetime.end
  104. ? {
  105. start: dataDatetime.start,
  106. end: dataDatetime.end,
  107. utc: dataDatetime.utc,
  108. }
  109. : {
  110. statsPeriod: dataDatetime.period || DEFAULT_STATS_PERIOD,
  111. };
  112. return queryDatetime;
  113. }
  114. get endpointQuery() {
  115. const {dataDatetime, projectIds, dataCategoryApiName} = this.props;
  116. const queryDatetime = this.endpointQueryDatetime;
  117. return {
  118. ...queryDatetime,
  119. interval: getSeriesApiInterval(dataDatetime),
  120. groupBy: ['outcome', 'reason'],
  121. project: projectIds,
  122. field: ['sum(quantity)'],
  123. category: dataCategoryApiName,
  124. };
  125. }
  126. get chartData(): {
  127. cardStats: {
  128. accepted?: string;
  129. filtered?: string;
  130. invalid?: string;
  131. rateLimited?: string;
  132. total?: string;
  133. };
  134. chartDateEnd: string;
  135. chartDateEndDisplay: string;
  136. chartDateInterval: IntervalPeriod;
  137. chartDateStart: string;
  138. chartDateStartDisplay: string;
  139. chartDateTimezoneDisplay: string;
  140. chartDateUtc: boolean;
  141. chartStats: ChartStats;
  142. chartSubLabels: TooltipSubLabel[];
  143. chartTransform: ChartDataTransform;
  144. dataError?: Error;
  145. } {
  146. return {
  147. ...mapSeriesToChart({
  148. orgStats: this.state.orgStats,
  149. chartDateInterval: this.chartDateRange.chartDateInterval,
  150. chartDateUtc: this.chartDateRange.chartDateUtc,
  151. dataCategory: this.props.dataCategory,
  152. endpointQuery: this.endpointQuery,
  153. }),
  154. ...this.chartDateRange,
  155. ...this.chartTransform,
  156. };
  157. }
  158. get chartTransform(): {chartTransform: ChartDataTransform} {
  159. const {chartTransform} = this.props;
  160. switch (chartTransform) {
  161. case ChartDataTransform.CUMULATIVE:
  162. case ChartDataTransform.PERIODIC:
  163. return {chartTransform};
  164. default:
  165. return {chartTransform: ChartDataTransform.PERIODIC};
  166. }
  167. }
  168. get chartDateRange(): {
  169. chartDateEnd: string;
  170. chartDateEndDisplay: string;
  171. chartDateInterval: IntervalPeriod;
  172. chartDateStart: string;
  173. chartDateStartDisplay: string;
  174. chartDateTimezoneDisplay: string;
  175. chartDateUtc: boolean;
  176. } {
  177. const {orgStats} = this.state;
  178. const {dataDatetime} = this.props;
  179. const interval = getSeriesApiInterval(dataDatetime);
  180. // Use fillers as loading/error states will not display datetime at all
  181. if (!orgStats || !orgStats.intervals) {
  182. return {
  183. chartDateInterval: interval,
  184. chartDateStart: '',
  185. chartDateEnd: '',
  186. chartDateUtc: true,
  187. chartDateStartDisplay: '',
  188. chartDateEndDisplay: '',
  189. chartDateTimezoneDisplay: '',
  190. };
  191. }
  192. const {intervals} = orgStats;
  193. const intervalHours = parsePeriodToHours(interval);
  194. // Keep datetime in UTC until we want to display it to users
  195. const startTime = moment(intervals[0]).utc();
  196. const endTime =
  197. intervals.length < 2
  198. ? moment(startTime) // when statsPeriod and interval is the same value
  199. : moment(intervals[intervals.length - 1]).utc();
  200. const useUtc = isDisplayUtc(dataDatetime);
  201. // If interval is a day or more, use UTC to format date. Otherwise, the date
  202. // may shift ahead/behind when converting to the user's local time.
  203. const FORMAT_DATETIME =
  204. intervalHours >= 24 ? FORMAT_DATETIME_DAILY : FORMAT_DATETIME_HOURLY;
  205. const xAxisStart = moment(startTime);
  206. const xAxisEnd = moment(endTime);
  207. const displayStart = useUtc ? moment(startTime).utc() : moment(startTime).local();
  208. const displayEnd = useUtc ? moment(endTime).utc() : moment(endTime).local();
  209. if (intervalHours < 24) {
  210. displayEnd.add(intervalHours, 'h');
  211. }
  212. return {
  213. chartDateInterval: interval,
  214. chartDateStart: xAxisStart.format(),
  215. chartDateEnd: xAxisEnd.format(),
  216. chartDateUtc: useUtc,
  217. chartDateStartDisplay: displayStart.format(FORMAT_DATETIME),
  218. chartDateEndDisplay: displayEnd.format(FORMAT_DATETIME),
  219. chartDateTimezoneDisplay: displayStart.format('Z'),
  220. };
  221. }
  222. get chartProps(): UsageChartProps {
  223. const {dataCategory, clientDiscard, handleChangeState} = this.props;
  224. const {error, errors, loading} = this.state;
  225. const {
  226. chartStats,
  227. dataError,
  228. chartDateInterval,
  229. chartDateStart,
  230. chartDateEnd,
  231. chartDateUtc,
  232. chartTransform,
  233. chartSubLabels,
  234. } = this.chartData;
  235. const hasError = error || !!dataError;
  236. const chartErrors: any = dataError ? {...errors, data: dataError} : errors; // TODO(ts): AsyncComponent
  237. const chartProps = {
  238. isLoading: loading,
  239. isError: hasError,
  240. errors: chartErrors,
  241. title: ' ', // Force the title to be blank
  242. footer: this.renderChartFooter(),
  243. dataCategory,
  244. dataTransform: chartTransform,
  245. usageDateStart: chartDateStart,
  246. usageDateEnd: chartDateEnd,
  247. usageDateShowUtc: chartDateUtc,
  248. usageDateInterval: chartDateInterval,
  249. usageStats: chartStats,
  250. chartTooltip: {
  251. subLabels: chartSubLabels,
  252. skipZeroValuedSubLabels: true,
  253. },
  254. legendSelected: {[SeriesTypes.CLIENT_DISCARD]: !!clientDiscard},
  255. onLegendSelectChanged: ({name, selected}) => {
  256. if (name === SeriesTypes.CLIENT_DISCARD) {
  257. handleChangeState({clientDiscard: selected[name]});
  258. }
  259. },
  260. } as UsageChartProps;
  261. return chartProps;
  262. }
  263. get cardMetadata() {
  264. const {
  265. dataCategory,
  266. dataCategoryName,
  267. organization,
  268. projectIds,
  269. router,
  270. dataCategoryApiName,
  271. } = this.props;
  272. const {total, accepted, invalid, rateLimited, filtered} = this.chartData.cardStats;
  273. const navigateToInboundFilterSettings = (event: ReactMouseEvent) => {
  274. event.preventDefault();
  275. const url = `/settings/${organization.slug}/projects/:projectId/filters/data-filters/`;
  276. if (router) {
  277. navigateTo(url, router);
  278. }
  279. };
  280. const cardMetadata: Record<string, ScoreCardProps> = {
  281. total: {
  282. title: tct('Total [dataCategory]', {dataCategory: dataCategoryName}),
  283. score: total,
  284. },
  285. accepted: {
  286. title: tct('Accepted [dataCategory]', {dataCategory: dataCategoryName}),
  287. help: tct('Accepted [dataCategory] were successfully processed by Sentry', {
  288. dataCategory,
  289. }),
  290. score: accepted,
  291. trend: (
  292. <UsageStatsPerMin
  293. dataCategoryApiName={dataCategoryApiName}
  294. dataCategory={dataCategory}
  295. organization={organization}
  296. projectIds={projectIds}
  297. />
  298. ),
  299. },
  300. filtered: {
  301. title: tct('Filtered [dataCategory]', {dataCategory: dataCategoryName}),
  302. help: tct(
  303. 'Filtered [dataCategory] were blocked due to your [filterSettings: inbound data filter] rules',
  304. {
  305. dataCategory,
  306. filterSettings: (
  307. <a href="#" onClick={event => navigateToInboundFilterSettings(event)} />
  308. ),
  309. }
  310. ),
  311. score: filtered,
  312. },
  313. rateLimited: {
  314. title: tct('Rate Limited [dataCategory]', {dataCategory: dataCategoryName}),
  315. help: tct(
  316. 'Rate Limited [dataCategory] were discarded due to rate limits or quota',
  317. {dataCategory}
  318. ),
  319. score: rateLimited,
  320. },
  321. invalid: {
  322. title: tct('Invalid [dataCategory]', {dataCategory: dataCategoryName}),
  323. help: tct(
  324. 'Invalid [dataCategory] were sent by the SDK and were discarded because the data did not meet the basic schema requirements',
  325. {dataCategory}
  326. ),
  327. score: invalid,
  328. },
  329. };
  330. return cardMetadata;
  331. }
  332. renderCards() {
  333. const {loading} = this.state;
  334. const cardMetadata = Object.values(this.cardMetadata);
  335. return cardMetadata.map((card, i) => (
  336. <StyledScoreCard
  337. key={i}
  338. title={card.title}
  339. score={loading ? undefined : card.score}
  340. help={card.help}
  341. trend={card.trend}
  342. isTooltipHoverable
  343. />
  344. ));
  345. }
  346. renderChart() {
  347. const {loading} = this.state;
  348. return <UsageChart {...this.chartProps} isLoading={loading} />;
  349. }
  350. renderChartFooter = () => {
  351. const {handleChangeState, clientDiscard} = this.props;
  352. const {loading, error} = this.state;
  353. const {
  354. chartDateInterval,
  355. chartTransform,
  356. chartDateStartDisplay,
  357. chartDateEndDisplay,
  358. chartDateTimezoneDisplay,
  359. } = this.chartData;
  360. return (
  361. <Footer>
  362. <InlineContainer>
  363. <FooterDate>
  364. <SectionHeading>{t('Date Range:')}</SectionHeading>
  365. <span>
  366. {loading || error ? (
  367. <NotAvailable />
  368. ) : (
  369. tct('[start] — [end] ([timezone] UTC, [interval] interval)', {
  370. start: chartDateStartDisplay,
  371. end: chartDateEndDisplay,
  372. timezone: chartDateTimezoneDisplay,
  373. interval: chartDateInterval,
  374. })
  375. )}
  376. </span>
  377. </FooterDate>
  378. </InlineContainer>
  379. <InlineContainer>
  380. {(this.chartData.chartStats.clientDiscard ?? []).length > 0 && (
  381. <Flex align="center" gap={space(1)}>
  382. <strong>{t('Show client-discarded data:')}</strong>
  383. <SwitchButton
  384. toggle={() => {
  385. handleChangeState({clientDiscard: !clientDiscard});
  386. }}
  387. isActive={clientDiscard}
  388. />
  389. </Flex>
  390. )}
  391. </InlineContainer>
  392. <InlineContainer>
  393. <OptionSelector
  394. title={t('Type')}
  395. selected={chartTransform}
  396. options={CHART_OPTIONS_DATA_TRANSFORM}
  397. onChange={(val: string) =>
  398. handleChangeState({transform: val as ChartDataTransform})
  399. }
  400. />
  401. </InlineContainer>
  402. </Footer>
  403. );
  404. };
  405. renderProjectDetails() {
  406. const {isSingleProject} = this.props;
  407. const projectDetails = this.projectDetails.map((projectDetailComponent, i) => (
  408. <ErrorBoundary mini key={i}>
  409. {projectDetailComponent}
  410. </ErrorBoundary>
  411. ));
  412. return isSingleProject ? projectDetails : null;
  413. }
  414. renderComponent() {
  415. return (
  416. <Fragment>
  417. <PageGrid>
  418. {this.renderCards()}
  419. <ChartWrapper data-test-id="usage-stats-chart">
  420. {this.renderChart()}
  421. </ChartWrapper>
  422. </PageGrid>
  423. {this.renderProjectDetails()}
  424. </Fragment>
  425. );
  426. }
  427. }
  428. export default UsageStatsOrganization;
  429. const PageGrid = styled('div')`
  430. display: grid;
  431. grid-template-columns: 1fr;
  432. gap: ${space(2)};
  433. @media (min-width: ${p => p.theme.breakpoints.small}) {
  434. grid-template-columns: repeat(2, 1fr);
  435. }
  436. @media (min-width: ${p => p.theme.breakpoints.large}) {
  437. grid-template-columns: repeat(5, 1fr);
  438. }
  439. `;
  440. const StyledScoreCard = styled(ScoreCard)`
  441. grid-column: auto / span 1;
  442. margin: 0;
  443. `;
  444. const ChartWrapper = styled('div')`
  445. grid-column: 1 / -1;
  446. `;
  447. const Footer = styled('div')`
  448. display: flex;
  449. flex-direction: row;
  450. flex-wrap: wrap;
  451. align-items: center;
  452. gap: ${space(1.5)};
  453. padding: ${space(1)} ${space(3)};
  454. border-top: 1px solid ${p => p.theme.border};
  455. > *:first-child {
  456. flex-grow: 1;
  457. }
  458. `;
  459. const FooterDate = styled('div')`
  460. display: flex;
  461. flex-direction: row;
  462. align-items: center;
  463. > ${SectionHeading} {
  464. margin-right: ${space(1.5)};
  465. }
  466. > span:last-child {
  467. font-weight: ${p => p.theme.fontWeightNormal};
  468. font-size: ${p => p.theme.fontSizeMedium};
  469. }
  470. `;