usageStatsOrg.tsx 19 KB

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