usageStatsProjects.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {LocationDescriptorObject} from 'history';
  5. import isEqual from 'lodash/isEqual';
  6. import type {DateTimeObject} from 'sentry/components/charts/utils';
  7. import {getSeriesApiInterval} from 'sentry/components/charts/utils';
  8. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  9. import type {Alignments, Directions} from 'sentry/components/gridEditable/sortLink';
  10. import SortLink from 'sentry/components/gridEditable/sortLink';
  11. import Pagination from 'sentry/components/pagination';
  12. import SearchBar from 'sentry/components/searchBar';
  13. import {DATA_CATEGORY_INFO, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  14. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {DataCategoryInfo} from 'sentry/types/core';
  18. import {Outcome} from 'sentry/types/core';
  19. import type {Organization} from 'sentry/types/organization';
  20. import type {Project} from 'sentry/types/project';
  21. import {hasDynamicSamplingCustomFeature} from 'sentry/utils/dynamicSampling/features';
  22. import withProjects from 'sentry/utils/withProjects';
  23. import type {UsageSeries} from './types';
  24. import type {TableStat} from './usageTable';
  25. import UsageTable, {CellProject, CellStat} from './usageTable';
  26. import {getOffsetFromCursor, getPaginationPageLink} from './utils';
  27. type Props = {
  28. dataCategory: DataCategoryInfo;
  29. dataCategoryName: string;
  30. dataDatetime: DateTimeObject;
  31. getNextLocations: (project: Project) => Record<string, LocationDescriptorObject>;
  32. handleChangeState: (
  33. nextState: {
  34. cursor?: string;
  35. query?: string;
  36. sort?: string;
  37. },
  38. options?: {willUpdateRouter?: boolean}
  39. ) => LocationDescriptorObject;
  40. isSingleProject: boolean;
  41. loadingProjects: boolean;
  42. organization: Organization;
  43. projectIds: number[];
  44. projects: Project[];
  45. tableCursor?: string;
  46. tableQuery?: string;
  47. tableSort?: string;
  48. } & DeprecatedAsyncComponent['props'];
  49. type State = {
  50. projectStats: UsageSeries | undefined;
  51. } & DeprecatedAsyncComponent['state'];
  52. export enum SortBy {
  53. PROJECT = 'project',
  54. TOTAL = 'total',
  55. ACCEPTED = 'accepted',
  56. ACCEPTED_STORED = 'accepted_stored',
  57. FILTERED = 'filtered',
  58. INVALID = 'invalid',
  59. RATE_LIMITED = 'rate_limited',
  60. }
  61. class UsageStatsProjects extends DeprecatedAsyncComponent<Props, State> {
  62. static MAX_ROWS_USAGE_TABLE = 25;
  63. componentDidUpdate(prevProps: Props) {
  64. const {
  65. dataDatetime: prevDateTime,
  66. dataCategory: prevDataCategory,
  67. projectIds: prevProjectIds,
  68. } = prevProps;
  69. const {
  70. dataDatetime: currDateTime,
  71. dataCategory: currDataCategory,
  72. projectIds: currProjectIds,
  73. } = this.props;
  74. if (
  75. prevDateTime.start !== currDateTime.start ||
  76. prevDateTime.end !== currDateTime.end ||
  77. prevDateTime.period !== currDateTime.period ||
  78. prevDateTime.utc !== currDateTime.utc ||
  79. prevDataCategory !== currDataCategory ||
  80. !isEqual(prevProjectIds, currProjectIds)
  81. ) {
  82. this.reloadData();
  83. }
  84. }
  85. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  86. return [['projectStats', this.endpointPath, {query: this.endpointQuery}]];
  87. }
  88. get endpointPath() {
  89. const {organization} = this.props;
  90. return `/organizations/${organization.slug}/stats_v2/`;
  91. }
  92. get endpointQuery() {
  93. const {dataDatetime, dataCategory, projectIds, isSingleProject} = this.props;
  94. const queryDatetime =
  95. dataDatetime.start && dataDatetime.end
  96. ? {
  97. start: dataDatetime.start,
  98. end: dataDatetime.end,
  99. utc: dataDatetime.utc,
  100. }
  101. : {
  102. statsPeriod: dataDatetime.period || DEFAULT_STATS_PERIOD,
  103. };
  104. const groupBy = ['outcome', 'project'];
  105. const category: string[] = [dataCategory.apiName];
  106. if (
  107. hasDynamicSamplingCustomFeature(this.props.organization) &&
  108. dataCategory.apiName === 'span'
  109. ) {
  110. groupBy.push('category');
  111. category.push('span_indexed');
  112. }
  113. // We do not need more granularity in the data so interval is '1d'
  114. return {
  115. ...queryDatetime,
  116. interval: getSeriesApiInterval(dataDatetime),
  117. groupBy,
  118. field: ['sum(quantity)'],
  119. // If only one project is in selected, display the entire project list
  120. project: isSingleProject ? [ALL_ACCESS_PROJECTS] : projectIds,
  121. category,
  122. };
  123. }
  124. get tableData() {
  125. const {projectStats} = this.state;
  126. const seriesData = this.mapSeriesToTable(projectStats);
  127. const showStoredOutcome =
  128. hasDynamicSamplingCustomFeature(this.props.organization) &&
  129. this.props.dataCategory.apiName === 'span' &&
  130. seriesData.hasStoredOutcome;
  131. return {
  132. headers: this.getTableHeader({showStoredOutcome}),
  133. showStoredOutcome,
  134. ...seriesData,
  135. };
  136. }
  137. get tableSort(): {
  138. direction: number;
  139. key: SortBy;
  140. } {
  141. const {tableSort} = this.props;
  142. if (!tableSort) {
  143. return {
  144. key: SortBy.TOTAL,
  145. direction: 1,
  146. };
  147. }
  148. let key: string = tableSort;
  149. let direction: number = -1;
  150. if (tableSort.charAt(0) === '-') {
  151. key = key.slice(1);
  152. direction = 1;
  153. }
  154. switch (key) {
  155. case SortBy.PROJECT:
  156. case SortBy.TOTAL:
  157. case SortBy.ACCEPTED:
  158. case SortBy.FILTERED:
  159. case SortBy.INVALID:
  160. case SortBy.RATE_LIMITED:
  161. return {key, direction};
  162. default:
  163. return {key: SortBy.ACCEPTED, direction: -1};
  164. }
  165. }
  166. get tableOffset() {
  167. const {tableCursor} = this.props;
  168. return getOffsetFromCursor(tableCursor);
  169. }
  170. /**
  171. * OrganizationStatsEndpointV2 does not have any performance issues. We use
  172. * client-side pagination to limit the number of rows on the table so the
  173. * page doesn't scroll too deeply for organizations with a lot of projects
  174. */
  175. get pageLink() {
  176. const offset = this.tableOffset;
  177. const numRows = this.filteredProjects.length;
  178. return getPaginationPageLink({
  179. numRows,
  180. pageSize: UsageStatsProjects.MAX_ROWS_USAGE_TABLE,
  181. offset,
  182. });
  183. }
  184. get projectSelectionFilter(): (p: Project) => boolean {
  185. const {projectIds, isSingleProject} = this.props;
  186. const selectedProjects = new Set(projectIds.map(id => `${id}`));
  187. // If 'My Projects' or 'All Projects' are selected
  188. return selectedProjects.size === 0 || selectedProjects.has('-1') || isSingleProject
  189. ? _p => true
  190. : p => selectedProjects.has(p.id);
  191. }
  192. /**
  193. * Filter projects if there's a query
  194. */
  195. get filteredProjects() {
  196. const {projects, tableQuery} = this.props;
  197. return tableQuery
  198. ? projects.filter(
  199. p =>
  200. p.slug.includes(tableQuery) && p.hasAccess && this.projectSelectionFilter(p)
  201. )
  202. : projects.filter(p => p.hasAccess && this.projectSelectionFilter(p));
  203. }
  204. getTableHeader({showStoredOutcome}: {showStoredOutcome: boolean}) {
  205. const {key, direction} = this.tableSort;
  206. const getArrowDirection = (linkKey: SortBy): Directions => {
  207. if (linkKey !== key) {
  208. return undefined;
  209. }
  210. return direction > 0 ? 'desc' : 'asc';
  211. };
  212. return [
  213. {
  214. key: SortBy.PROJECT,
  215. title: t('Project'),
  216. align: 'left',
  217. direction: getArrowDirection(SortBy.PROJECT),
  218. onClick: () => this.handleChangeSort(SortBy.PROJECT),
  219. },
  220. {
  221. key: SortBy.TOTAL,
  222. title: t('Total'),
  223. align: 'right',
  224. direction: getArrowDirection(SortBy.TOTAL),
  225. onClick: () => this.handleChangeSort(SortBy.TOTAL),
  226. },
  227. {
  228. key: SortBy.ACCEPTED,
  229. title: showStoredOutcome ? t('Accepted (Stored)') : t('Accepted'),
  230. align: 'right',
  231. direction: getArrowDirection(SortBy.ACCEPTED),
  232. onClick: () => this.handleChangeSort(SortBy.ACCEPTED),
  233. },
  234. {
  235. key: SortBy.FILTERED,
  236. title: t('Filtered'),
  237. align: 'right',
  238. direction: getArrowDirection(SortBy.FILTERED),
  239. onClick: () => this.handleChangeSort(SortBy.FILTERED),
  240. },
  241. {
  242. key: SortBy.RATE_LIMITED,
  243. title: t('Rate Limited'),
  244. align: 'right',
  245. direction: getArrowDirection(SortBy.RATE_LIMITED),
  246. onClick: () => this.handleChangeSort(SortBy.RATE_LIMITED),
  247. },
  248. {
  249. key: SortBy.INVALID,
  250. title: t('Invalid'),
  251. align: 'right',
  252. direction: getArrowDirection(SortBy.INVALID),
  253. onClick: () => this.handleChangeSort(SortBy.INVALID),
  254. },
  255. ]
  256. .map(h => {
  257. const Cell = h.key === SortBy.PROJECT ? CellProject : CellStat;
  258. return (
  259. <Cell key={h.key}>
  260. <SortLink
  261. canSort
  262. title={h.title}
  263. align={h.align as Alignments}
  264. direction={h.direction}
  265. generateSortLink={h.onClick}
  266. />
  267. </Cell>
  268. );
  269. })
  270. .concat([<CellStat key="empty" />]); // Extra column for displaying buttons etc.
  271. }
  272. getProjectLink(project: Project) {
  273. const {dataCategory, getNextLocations, organization} = this.props;
  274. const {performance, projectDetail, settings} = getNextLocations(project);
  275. if (
  276. dataCategory === DATA_CATEGORY_INFO.transaction &&
  277. organization.features.includes('performance-view')
  278. ) {
  279. return {
  280. projectLink: performance,
  281. projectSettingsLink: settings,
  282. };
  283. }
  284. return {
  285. projectLink: projectDetail,
  286. projectSettingsLink: settings,
  287. };
  288. }
  289. handleChangeSort = (nextKey: SortBy) => {
  290. const {handleChangeState} = this.props;
  291. const {key, direction} = this.tableSort;
  292. let nextDirection = 1; // Default to descending
  293. if (key === nextKey) {
  294. nextDirection = direction * -1; // Toggle if clicking on the same column
  295. } else if (nextKey === SortBy.PROJECT) {
  296. nextDirection = -1; // Default PROJECT to ascending
  297. }
  298. // The header uses SortLink, which takes a LocationDescriptor and pushes
  299. // that to the router. As such, we do not need to update the router in
  300. // handleChangeState
  301. return handleChangeState(
  302. {sort: `${nextDirection > 0 ? '-' : ''}${nextKey}`},
  303. {willUpdateRouter: false}
  304. );
  305. };
  306. handleSearch = (query: string) => {
  307. const {handleChangeState, tableQuery} = this.props;
  308. if (query === tableQuery) {
  309. return;
  310. }
  311. if (!query) {
  312. handleChangeState({query: undefined, cursor: undefined});
  313. return;
  314. }
  315. handleChangeState({query, cursor: undefined});
  316. };
  317. mapSeriesToTable(projectStats?: UsageSeries): {
  318. hasStoredOutcome: boolean;
  319. tableStats: TableStat[];
  320. error?: Error;
  321. } {
  322. if (!projectStats) {
  323. return {tableStats: [], hasStoredOutcome: false};
  324. }
  325. const stats: Record<number, object> = {};
  326. try {
  327. const baseStat: Partial<TableStat> = {
  328. [SortBy.TOTAL]: 0,
  329. [SortBy.ACCEPTED]: 0,
  330. [SortBy.ACCEPTED_STORED]: 0,
  331. [SortBy.FILTERED]: 0,
  332. [SortBy.INVALID]: 0,
  333. [SortBy.RATE_LIMITED]: 0,
  334. };
  335. const projectList = this.filteredProjects;
  336. const projectSet = new Set(projectList.map(p => p.id));
  337. projectStats.groups.forEach(group => {
  338. const {outcome, category, project: projectId} = group.by;
  339. // Backend enum is singlar. Frontend enum is plural.
  340. if (category === 'span_indexed' && outcome !== Outcome.ACCEPTED) {
  341. // we need `span_indexed` data for `accepted_stored` only
  342. return;
  343. }
  344. if (!projectSet.has(projectId.toString())) {
  345. return;
  346. }
  347. if (!stats[projectId]) {
  348. stats[projectId] = {...baseStat};
  349. }
  350. if (outcome !== Outcome.CLIENT_DISCARD && category !== 'span_indexed') {
  351. stats[projectId].total += group.totals['sum(quantity)'];
  352. }
  353. if (category === 'span_indexed' && outcome === Outcome.ACCEPTED) {
  354. stats[projectId].accepted_stored += group.totals['sum(quantity)'];
  355. return;
  356. }
  357. if (
  358. outcome === Outcome.ACCEPTED ||
  359. outcome === Outcome.FILTERED ||
  360. outcome === Outcome.INVALID
  361. ) {
  362. stats[projectId][outcome] += group.totals['sum(quantity)'];
  363. }
  364. if (
  365. outcome === Outcome.RATE_LIMITED ||
  366. outcome === Outcome.CARDINALITY_LIMITED ||
  367. outcome === Outcome.ABUSE
  368. ) {
  369. stats[projectId][SortBy.RATE_LIMITED] += group.totals['sum(quantity)'];
  370. }
  371. });
  372. // For projects without stats, fill in with zero
  373. let hasStoredOutcome = false;
  374. const tableStats: TableStat[] = projectList.map(proj => {
  375. const stat = stats[proj.id] ?? {...baseStat};
  376. if (
  377. stat[SortBy.ACCEPTED_STORED] > 0 &&
  378. stat[SortBy.ACCEPTED_STORED] !== stat[SortBy.ACCEPTED]
  379. ) {
  380. hasStoredOutcome = true;
  381. }
  382. return {
  383. project: {...proj},
  384. ...this.getProjectLink(proj),
  385. ...stat,
  386. };
  387. });
  388. const {key, direction} = this.tableSort;
  389. tableStats.sort((a, b) => {
  390. if (key === SortBy.PROJECT) {
  391. return b.project.slug.localeCompare(a.project.slug) * direction;
  392. }
  393. return a[key] !== b[key]
  394. ? (b[key] - a[key]) * direction
  395. : a.project.slug.localeCompare(b.project.slug);
  396. });
  397. const offset = this.tableOffset;
  398. return {
  399. tableStats: tableStats.slice(
  400. offset,
  401. offset + UsageStatsProjects.MAX_ROWS_USAGE_TABLE
  402. ),
  403. hasStoredOutcome,
  404. };
  405. } catch (err) {
  406. Sentry.withScope(scope => {
  407. scope.setContext('query', this.endpointQuery);
  408. scope.setContext('body', {...projectStats});
  409. Sentry.captureException(err);
  410. });
  411. return {
  412. tableStats: [],
  413. hasStoredOutcome: false,
  414. error: err,
  415. };
  416. }
  417. }
  418. renderComponent() {
  419. const {error, errors, loading} = this.state;
  420. const {dataCategory, loadingProjects, tableQuery, isSingleProject} = this.props;
  421. const {headers, tableStats, showStoredOutcome} = this.tableData;
  422. return (
  423. <Fragment>
  424. {isSingleProject && (
  425. <PanelHeading>
  426. <Title>{t('All Projects')}</Title>
  427. </PanelHeading>
  428. )}
  429. {!isSingleProject && (
  430. <Container>
  431. <SearchBar
  432. defaultQuery=""
  433. query={tableQuery}
  434. placeholder={t('Filter your projects')}
  435. aria-label={t('Filter projects')}
  436. onSearch={this.handleSearch}
  437. />
  438. </Container>
  439. )}
  440. <Container data-test-id="usage-stats-table">
  441. <UsageTable
  442. isLoading={loading || loadingProjects}
  443. isError={error}
  444. errors={errors as any} // TODO(ts)
  445. isEmpty={tableStats.length === 0}
  446. headers={headers}
  447. dataCategory={dataCategory}
  448. usageStats={tableStats}
  449. showStoredOutcome={showStoredOutcome}
  450. />
  451. <Pagination pageLinks={this.pageLink} />
  452. </Container>
  453. </Fragment>
  454. );
  455. }
  456. }
  457. export default withProjects(UsageStatsProjects);
  458. const Container = styled('div')`
  459. margin-bottom: ${space(2)};
  460. `;
  461. const Title = styled('div')`
  462. font-weight: ${p => p.theme.fontWeightBold};
  463. font-size: ${p => p.theme.fontSizeLarge};
  464. color: ${p => p.theme.gray400};
  465. display: flex;
  466. flex: 1;
  467. align-items: center;
  468. `;
  469. const PanelHeading = styled('div')`
  470. display: flex;
  471. margin-bottom: ${space(2)};
  472. align-items: center;
  473. `;