usageStatsOrg.tsx 18 KB

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