usageStatsOrg.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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 {hasCustomMetrics} 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 (hasCustomMetrics(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 navigateToMetricsSettings = (event: ReactMouseEvent) => {
  283. event.preventDefault();
  284. const url = `/settings/${organization.slug}/projects/:projectId/metrics/`;
  285. if (router) {
  286. navigateTo(url, router);
  287. }
  288. };
  289. const cardMetadata: Record<string, ScoreCardProps> = {
  290. total: {
  291. title: tct('Total [dataCategory]', {dataCategory: dataCategoryName}),
  292. score: total,
  293. },
  294. accepted: {
  295. title: tct('Accepted [dataCategory]', {dataCategory: dataCategoryName}),
  296. help: tct('Accepted [dataCategory] were successfully processed by Sentry', {
  297. dataCategory,
  298. }),
  299. score: accepted,
  300. trend: (
  301. <UsageStatsPerMin
  302. dataCategory={dataCategory}
  303. organization={organization}
  304. projectIds={projectIds}
  305. />
  306. ),
  307. },
  308. filtered: {
  309. title: tct('Filtered [dataCategory]', {dataCategory: dataCategoryName}),
  310. help:
  311. dataCategory === DATA_CATEGORY_INFO.metrics.plural
  312. ? tct(
  313. 'Filtered metrics were blocked due to your disabled metrics [settings: settings]',
  314. {
  315. dataCategory,
  316. settings: (
  317. <a href="#" onClick={event => navigateToMetricsSettings(event)} />
  318. ),
  319. }
  320. )
  321. : tct(
  322. 'Filtered [dataCategory] were blocked due to your [filterSettings: inbound data filter] rules',
  323. {
  324. dataCategory,
  325. filterSettings: (
  326. <a
  327. href="#"
  328. onClick={event => navigateToInboundFilterSettings(event)}
  329. />
  330. ),
  331. }
  332. ),
  333. score: filtered,
  334. },
  335. dropped: {
  336. title: tct('Dropped [dataCategory]', {dataCategory: dataCategoryName}),
  337. help: tct(
  338. 'Dropped [dataCategory] were discarded due to invalid data, rate-limits, quota limits, or spike protection',
  339. {dataCategory}
  340. ),
  341. score: dropped,
  342. },
  343. };
  344. return cardMetadata;
  345. }
  346. mapSeriesToChart(orgStats?: UsageSeries): {
  347. cardStats: {
  348. accepted?: string;
  349. dropped?: string;
  350. filtered?: string;
  351. total?: string;
  352. };
  353. chartStats: ChartStats;
  354. dataError?: Error;
  355. } {
  356. const cardStats = {
  357. total: undefined,
  358. accepted: undefined,
  359. dropped: undefined,
  360. filtered: undefined,
  361. };
  362. const chartStats: ChartStats = {
  363. accepted: [],
  364. dropped: [],
  365. projected: [],
  366. filtered: [],
  367. };
  368. if (!orgStats) {
  369. return {cardStats, chartStats};
  370. }
  371. try {
  372. const {dataCategory} = this.props;
  373. const {chartDateInterval, chartDateUtc} = this.chartDateRange;
  374. const usageStats: UsageStat[] = orgStats.intervals.map(interval => {
  375. const dateTime = moment(interval);
  376. return {
  377. date: getDateFromMoment(dateTime, chartDateInterval, chartDateUtc),
  378. total: 0,
  379. accepted: 0,
  380. filtered: 0,
  381. dropped: {total: 0},
  382. };
  383. });
  384. // Tally totals for card data
  385. const count: Record<'total' | Outcome, number> = {
  386. total: 0,
  387. [Outcome.ACCEPTED]: 0,
  388. [Outcome.FILTERED]: 0,
  389. [Outcome.DROPPED]: 0,
  390. [Outcome.INVALID]: 0, // Combined with dropped later
  391. [Outcome.RATE_LIMITED]: 0, // Combined with dropped later
  392. [Outcome.CLIENT_DISCARD]: 0, // Not exposed yet
  393. [Outcome.CARDINALITY_LIMITED]: 0, // Combined with dropped later
  394. };
  395. orgStats.groups.forEach(group => {
  396. const {outcome, category} = group.by;
  397. // HACK: The backend enum are singular, but the frontend enums are plural
  398. if (!dataCategory.includes(`${category}`)) {
  399. return;
  400. }
  401. if (outcome !== Outcome.CLIENT_DISCARD) {
  402. count.total += group.totals['sum(quantity)'];
  403. }
  404. count[outcome] += group.totals['sum(quantity)'];
  405. group.series['sum(quantity)'].forEach((stat, i) => {
  406. switch (outcome) {
  407. case Outcome.ACCEPTED:
  408. case Outcome.FILTERED:
  409. usageStats[i][outcome] += stat;
  410. return;
  411. case Outcome.DROPPED:
  412. case Outcome.RATE_LIMITED:
  413. case Outcome.CARDINALITY_LIMITED:
  414. case Outcome.INVALID:
  415. usageStats[i].dropped.total += stat;
  416. // TODO: add client discards to dropped?
  417. return;
  418. default:
  419. return;
  420. }
  421. });
  422. });
  423. // Invalid and rate_limited data is combined with dropped
  424. count[Outcome.DROPPED] += count[Outcome.INVALID];
  425. count[Outcome.DROPPED] += count[Outcome.RATE_LIMITED];
  426. count[Outcome.DROPPED] += count[Outcome.CARDINALITY_LIMITED];
  427. usageStats.forEach(stat => {
  428. stat.total = stat.accepted + stat.filtered + stat.dropped.total;
  429. // Chart Data
  430. (chartStats.accepted as any[]).push({value: [stat.date, stat.accepted]});
  431. (chartStats.dropped as any[]).push({
  432. value: [stat.date, stat.dropped.total],
  433. } as any);
  434. (chartStats.filtered as any[])?.push({value: [stat.date, stat.filtered]});
  435. });
  436. return {
  437. cardStats: {
  438. total: formatUsageWithUnits(
  439. count.total,
  440. dataCategory,
  441. getFormatUsageOptions(dataCategory)
  442. ),
  443. accepted: formatUsageWithUnits(
  444. count[Outcome.ACCEPTED],
  445. dataCategory,
  446. getFormatUsageOptions(dataCategory)
  447. ),
  448. filtered: formatUsageWithUnits(
  449. count[Outcome.FILTERED],
  450. dataCategory,
  451. getFormatUsageOptions(dataCategory)
  452. ),
  453. dropped: formatUsageWithUnits(
  454. count[Outcome.DROPPED],
  455. dataCategory,
  456. getFormatUsageOptions(dataCategory)
  457. ),
  458. },
  459. chartStats,
  460. };
  461. } catch (err) {
  462. Sentry.withScope(scope => {
  463. scope.setContext('query', this.endpointQuery);
  464. scope.setContext('body', {...orgStats});
  465. Sentry.captureException(err);
  466. });
  467. return {
  468. cardStats,
  469. chartStats,
  470. dataError: new Error('Failed to parse stats data'),
  471. };
  472. }
  473. }
  474. renderCards() {
  475. const {loading} = this.state;
  476. const cardMetadata = Object.values(this.cardMetadata);
  477. return cardMetadata.map((card, i) => (
  478. <StyledScoreCard
  479. key={i}
  480. title={card.title}
  481. score={loading ? undefined : card.score}
  482. help={card.help}
  483. trend={card.trend}
  484. isTooltipHoverable
  485. />
  486. ));
  487. }
  488. renderChart() {
  489. const {loading} = this.state;
  490. return <UsageChart {...this.chartProps} isLoading={loading} />;
  491. }
  492. renderChartFooter = () => {
  493. const {handleChangeState} = this.props;
  494. const {loading, error} = this.state;
  495. const {
  496. chartDateInterval,
  497. chartTransform,
  498. chartDateStartDisplay,
  499. chartDateEndDisplay,
  500. chartDateTimezoneDisplay,
  501. } = this.chartData;
  502. return (
  503. <Footer>
  504. <InlineContainer>
  505. <FooterDate>
  506. <SectionHeading>{t('Date Range:')}</SectionHeading>
  507. <span>
  508. {loading || error ? (
  509. <NotAvailable />
  510. ) : (
  511. tct('[start] — [end] ([timezone] UTC, [interval] interval)', {
  512. start: chartDateStartDisplay,
  513. end: chartDateEndDisplay,
  514. timezone: chartDateTimezoneDisplay,
  515. interval: chartDateInterval,
  516. })
  517. )}
  518. </span>
  519. </FooterDate>
  520. </InlineContainer>
  521. <InlineContainer>
  522. <OptionSelector
  523. title={t('Type')}
  524. selected={chartTransform}
  525. options={CHART_OPTIONS_DATA_TRANSFORM}
  526. onChange={(val: string) =>
  527. handleChangeState({transform: val as ChartDataTransform})
  528. }
  529. />
  530. </InlineContainer>
  531. </Footer>
  532. );
  533. };
  534. renderProjectDetails() {
  535. const {isSingleProject} = this.props;
  536. const projectDetails = this.projectDetails.map((projectDetailComponent, i) => (
  537. <ErrorBoundary mini key={i}>
  538. {projectDetailComponent}
  539. </ErrorBoundary>
  540. ));
  541. return isSingleProject ? projectDetails : null;
  542. }
  543. renderComponent() {
  544. return (
  545. <Fragment>
  546. <PageGrid>
  547. {this.renderCards()}
  548. <ChartWrapper data-test-id="usage-stats-chart">
  549. {this.renderChart()}
  550. </ChartWrapper>
  551. </PageGrid>
  552. {this.renderProjectDetails()}
  553. </Fragment>
  554. );
  555. }
  556. }
  557. export default UsageStatsOrganization;
  558. const PageGrid = styled('div')`
  559. display: grid;
  560. grid-template-columns: 1fr;
  561. gap: ${space(2)};
  562. @media (min-width: ${p => p.theme.breakpoints.small}) {
  563. grid-template-columns: repeat(2, 1fr);
  564. }
  565. @media (min-width: ${p => p.theme.breakpoints.large}) {
  566. grid-template-columns: repeat(4, 1fr);
  567. }
  568. `;
  569. const StyledScoreCard = styled(ScoreCard)`
  570. grid-column: auto / span 1;
  571. margin: 0;
  572. `;
  573. const ChartWrapper = styled('div')`
  574. grid-column: 1 / -1;
  575. `;
  576. const Footer = styled('div')`
  577. display: flex;
  578. flex-direction: row;
  579. justify-content: space-between;
  580. padding: ${space(1)} ${space(3)};
  581. border-top: 1px solid ${p => p.theme.border};
  582. `;
  583. const FooterDate = styled('div')`
  584. display: flex;
  585. flex-direction: row;
  586. align-items: center;
  587. > ${SectionHeading} {
  588. margin-right: ${space(1.5)};
  589. }
  590. > span:last-child {
  591. font-weight: 400;
  592. font-size: ${p => p.theme.fontSizeMedium};
  593. }
  594. `;