usageStatsProjects.tsx 14 KB

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