usageStatsProjects.tsx 14 KB

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