table.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  1. import {Component, Fragment} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location, LocationDescriptorObject} from 'history';
  5. import {addSuccessMessage} from 'sentry/actionCreators/indicator';
  6. import {openModal} from 'sentry/actionCreators/modal';
  7. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  8. import GridEditable, {
  9. COL_WIDTH_UNDEFINED,
  10. GridColumn,
  11. } from 'sentry/components/gridEditable';
  12. import SortLink from 'sentry/components/gridEditable/sortLink';
  13. import Link from 'sentry/components/links/link';
  14. import Pagination from 'sentry/components/pagination';
  15. import {Tooltip} from 'sentry/components/tooltip';
  16. import {IconStar} from 'sentry/icons';
  17. import {tct} from 'sentry/locale';
  18. import {Organization, Project} from 'sentry/types';
  19. import {trackAnalytics} from 'sentry/utils/analytics';
  20. import DiscoverQuery, {
  21. TableData,
  22. TableDataRow,
  23. } from 'sentry/utils/discover/discoverQuery';
  24. import EventView, {isFieldSortable, MetaType} from 'sentry/utils/discover/eventView';
  25. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  26. import {fieldAlignment, getAggregateAlias} from 'sentry/utils/discover/fields';
  27. import {MEPConsumer} from 'sentry/utils/performance/contexts/metricsEnhancedSetting';
  28. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  29. import CellAction, {Actions, updateQuery} from 'sentry/views/discover/table/cellAction';
  30. import {TableColumn} from 'sentry/views/discover/table/types';
  31. import {getMEPQueryParams} from './landing/widgets/utils';
  32. import TransactionThresholdModal, {
  33. modalCss,
  34. TransactionThresholdMetric,
  35. } from './transactionSummary/transactionThresholdModal';
  36. import {
  37. normalizeSearchConditionsWithTransactionName,
  38. transactionSummaryRouteWithQuery,
  39. } from './transactionSummary/utils';
  40. import {COLUMN_TITLES} from './data';
  41. import {
  42. areMultipleProjectsSelected,
  43. createUnnamedTransactionsDiscoverTarget,
  44. getProjectID,
  45. getSelectedProjectPlatforms,
  46. UNPARAMETERIZED_TRANSACTION,
  47. } from './utils';
  48. type Props = {
  49. eventView: EventView;
  50. location: Location;
  51. organization: Organization;
  52. projects: Project[];
  53. setError: (msg: string | undefined) => void;
  54. withStaticFilters: boolean;
  55. columnTitles?: string[];
  56. summaryConditions?: string;
  57. };
  58. type State = {
  59. transaction: string | undefined;
  60. transactionThreshold: number | undefined;
  61. transactionThresholdMetric: TransactionThresholdMetric | undefined;
  62. widths: number[];
  63. };
  64. function getProjectFirstEventGroup(project: Project): '14d' | '30d' | '>30d' {
  65. const fourteen_days_ago = new Date(+new Date() - 12096e5);
  66. const thirty_days_ago = new Date(+new Date() - 25920e5);
  67. const firstEventDate = new Date(project?.firstEvent ?? '');
  68. if (firstEventDate > fourteen_days_ago) {
  69. return '14d';
  70. }
  71. if (firstEventDate > thirty_days_ago) {
  72. return '30d';
  73. }
  74. return '>30d';
  75. }
  76. class _Table extends Component<Props, State> {
  77. state: State = {
  78. widths: [],
  79. transaction: undefined,
  80. transactionThreshold: undefined,
  81. transactionThresholdMetric: undefined,
  82. };
  83. componentDidMount(): void {
  84. const {organization} = this.props;
  85. if (!this.tableMetricSet) {
  86. this.tableMetricSet = true;
  87. trackAnalytics('performance_views.landing.table.seen', {
  88. organization,
  89. });
  90. }
  91. }
  92. unparameterizedMetricSet = false;
  93. tableMetricSet = false;
  94. sendUnparameterizedAnalytic() {
  95. const {organization, eventView} = this.props;
  96. const statsPeriod = eventView.statsPeriod ?? 'other';
  97. const firstEventData = this.getFirstEventData();
  98. trackAnalytics('performance_views.landing.table.unparameterized', {
  99. organization,
  100. first_event: firstEventData.firstEventWithin,
  101. sent_transaction: firstEventData.singleProject?.firstTransactionEvent ?? false,
  102. single_project: firstEventData.isSingleProject,
  103. stats_period: statsPeriod,
  104. hit_multi_project_cap: firstEventData.isAtMultiCap,
  105. });
  106. }
  107. /**
  108. * Used for cluster warning and analytics.
  109. */
  110. getFirstEventData() {
  111. const {eventView, projects} = this.props;
  112. const isSingleProject = !areMultipleProjectsSelected(eventView);
  113. const selectedProjects = eventView.getFullSelectedProjects(projects);
  114. const isAtMultiCap = selectedProjects.length > 1000;
  115. const singleProject = selectedProjects[0];
  116. let firstEventWithin: 'none' | '14d' | '30d' | '>30d' = '>30d';
  117. if (isSingleProject) {
  118. firstEventWithin = getProjectFirstEventGroup(singleProject);
  119. } else if (!isAtMultiCap) {
  120. const dateGroups = selectedProjects.map(getProjectFirstEventGroup);
  121. if (dateGroups.every(g => g === '14d')) {
  122. firstEventWithin = '14d';
  123. }
  124. if (dateGroups.every(g => g === '14d' || g === '30d')) {
  125. firstEventWithin = '30d';
  126. }
  127. }
  128. return {
  129. firstEventWithin,
  130. isSingleProject,
  131. singleProject,
  132. isAtMultiCap,
  133. };
  134. }
  135. handleCellAction = (column: TableColumn<keyof TableDataRow>, dataRow: TableDataRow) => {
  136. return (action: Actions, value: React.ReactText) => {
  137. const {eventView, location, organization, projects} = this.props;
  138. trackAnalytics('performance_views.overview.cellaction', {
  139. organization,
  140. action,
  141. });
  142. if (action === Actions.EDIT_THRESHOLD) {
  143. const project_threshold = dataRow.project_threshold_config;
  144. const transactionName = dataRow.transaction as string;
  145. const projectID = getProjectID(dataRow, projects);
  146. openModal(
  147. modalProps => (
  148. <TransactionThresholdModal
  149. {...modalProps}
  150. organization={organization}
  151. transactionName={transactionName}
  152. eventView={eventView}
  153. project={projectID}
  154. transactionThreshold={project_threshold[1]}
  155. transactionThresholdMetric={project_threshold[0]}
  156. onApply={(threshold, metric) => {
  157. if (
  158. threshold !== project_threshold[1] ||
  159. metric !== project_threshold[0]
  160. ) {
  161. this.setState({
  162. transaction: transactionName,
  163. transactionThreshold: threshold,
  164. transactionThresholdMetric: metric,
  165. });
  166. }
  167. addSuccessMessage(
  168. tct('[transactionName] updated successfully', {
  169. transactionName,
  170. })
  171. );
  172. }}
  173. />
  174. ),
  175. {modalCss, closeEvents: 'escape-key'}
  176. );
  177. return;
  178. }
  179. const searchConditions = normalizeSearchConditionsWithTransactionName(
  180. eventView.query
  181. );
  182. updateQuery(searchConditions, action, column, value);
  183. browserHistory.push({
  184. pathname: location.pathname,
  185. query: {
  186. ...location.query,
  187. cursor: undefined,
  188. query: searchConditions.formatString(),
  189. },
  190. });
  191. };
  192. };
  193. renderBodyCell(
  194. tableData: TableData | null,
  195. column: TableColumn<keyof TableDataRow>,
  196. dataRow: TableDataRow
  197. ): React.ReactNode {
  198. const {eventView, organization, projects, location, withStaticFilters} = this.props;
  199. if (!tableData || !tableData.meta) {
  200. return dataRow[column.key];
  201. }
  202. const tableMeta = tableData.meta;
  203. const field = String(column.key);
  204. const fieldRenderer = getFieldRenderer(field, tableMeta, false);
  205. const rendered = fieldRenderer(dataRow, {organization, location});
  206. const allowActions = [
  207. Actions.ADD,
  208. Actions.EXCLUDE,
  209. Actions.SHOW_GREATER_THAN,
  210. Actions.SHOW_LESS_THAN,
  211. Actions.EDIT_THRESHOLD,
  212. ];
  213. const cellActions = withStaticFilters ? [] : allowActions;
  214. const isUnparameterizedRow = dataRow.transaction === UNPARAMETERIZED_TRANSACTION;
  215. if (field === 'transaction') {
  216. const projectID = getProjectID(dataRow, projects);
  217. const summaryView = eventView.clone();
  218. if (dataRow['http.method']) {
  219. summaryView.additionalConditions.setFilterValues('http.method', [
  220. dataRow['http.method'] as string,
  221. ]);
  222. }
  223. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  224. if (isUnparameterizedRow && !this.unparameterizedMetricSet) {
  225. this.sendUnparameterizedAnalytic();
  226. this.unparameterizedMetricSet = true;
  227. }
  228. const target = isUnparameterizedRow
  229. ? createUnnamedTransactionsDiscoverTarget({
  230. organization,
  231. location,
  232. })
  233. : transactionSummaryRouteWithQuery({
  234. orgSlug: organization.slug,
  235. transaction: String(dataRow.transaction) || '',
  236. query: summaryView.generateQueryStringObject(),
  237. projectID,
  238. });
  239. return (
  240. <CellAction
  241. column={column}
  242. dataRow={dataRow}
  243. handleCellAction={this.handleCellAction(column, dataRow)}
  244. allowActions={cellActions}
  245. >
  246. <Link
  247. to={target}
  248. onClick={this.handleSummaryClick}
  249. style={{display: `block`, width: `100%`}}
  250. >
  251. {rendered}
  252. </Link>
  253. </CellAction>
  254. );
  255. }
  256. if (field.startsWith('team_key_transaction')) {
  257. // don't display per cell actions for team_key_transaction
  258. return rendered;
  259. }
  260. const fieldName = getAggregateAlias(field);
  261. const value = dataRow[fieldName];
  262. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  263. return (
  264. <Tooltip
  265. title={value.toLocaleString()}
  266. containerDisplayMode="block"
  267. position="right"
  268. >
  269. <CellAction
  270. column={column}
  271. dataRow={dataRow}
  272. handleCellAction={this.handleCellAction(column, dataRow)}
  273. allowActions={cellActions}
  274. >
  275. {rendered}
  276. </CellAction>
  277. </Tooltip>
  278. );
  279. }
  280. return (
  281. <CellAction
  282. column={column}
  283. dataRow={dataRow}
  284. handleCellAction={this.handleCellAction(column, dataRow)}
  285. allowActions={cellActions}
  286. >
  287. {rendered}
  288. </CellAction>
  289. );
  290. }
  291. renderBodyCellWithData = (tableData: TableData | null) => {
  292. return (
  293. column: TableColumn<keyof TableDataRow>,
  294. dataRow: TableDataRow
  295. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  296. };
  297. onSortClick(currentSortKind?: string, currentSortField?: string) {
  298. const {organization} = this.props;
  299. trackAnalytics('performance_views.landingv2.transactions.sort', {
  300. organization,
  301. field: currentSortField,
  302. direction: currentSortKind,
  303. });
  304. }
  305. paginationAnalyticsEvent = (direction: string) => {
  306. const {organization} = this.props;
  307. trackAnalytics('performance_views.landingv3.table_pagination', {
  308. organization,
  309. direction,
  310. });
  311. };
  312. renderHeadCell(
  313. tableMeta: TableData['meta'],
  314. column: TableColumn<keyof TableDataRow>,
  315. title: React.ReactNode
  316. ): React.ReactNode {
  317. const {eventView, location} = this.props;
  318. const align = fieldAlignment(column.name, column.type, tableMeta);
  319. const field = {field: column.name, width: column.width};
  320. const aggregateAliasTableMeta: MetaType = {};
  321. if (tableMeta) {
  322. Object.keys(tableMeta).forEach(key => {
  323. aggregateAliasTableMeta[getAggregateAlias(key)] = tableMeta[key];
  324. });
  325. }
  326. function generateSortLink(): LocationDescriptorObject | undefined {
  327. if (!tableMeta) {
  328. return undefined;
  329. }
  330. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  331. const queryStringObject = nextEventView.generateQueryStringObject();
  332. return {
  333. ...location,
  334. query: {...location.query, sort: queryStringObject.sort},
  335. };
  336. }
  337. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  338. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  339. const currentSortKind = currentSort ? currentSort.kind : undefined;
  340. const currentSortField = currentSort ? currentSort.field : undefined;
  341. const sortLink = (
  342. <SortLink
  343. align={align}
  344. title={title || field.field}
  345. direction={currentSortKind}
  346. canSort={canSort}
  347. generateSortLink={generateSortLink}
  348. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  349. />
  350. );
  351. if (field.field.startsWith('user_misery')) {
  352. return (
  353. <GuideAnchor target="project_transaction_threshold" position="top">
  354. {sortLink}
  355. </GuideAnchor>
  356. );
  357. }
  358. return sortLink;
  359. }
  360. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  361. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  362. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  363. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  364. };
  365. renderPrependCellWithData = (tableData: TableData | null) => {
  366. const {eventView} = this.props;
  367. const teamKeyTransactionColumn = eventView
  368. .getColumns()
  369. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  370. return (isHeader: boolean, dataRow?: any) => {
  371. if (teamKeyTransactionColumn) {
  372. if (isHeader) {
  373. const star = (
  374. <TeamKeyTransactionWrapper>
  375. <IconStar
  376. key="keyTransaction"
  377. color="yellow400"
  378. isSolid
  379. data-test-id="team-key-transaction-header"
  380. />
  381. </TeamKeyTransactionWrapper>
  382. );
  383. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  384. }
  385. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  386. }
  387. return [];
  388. };
  389. };
  390. handleSummaryClick = () => {
  391. const {organization, location, projects} = this.props;
  392. trackAnalytics('performance_views.overview.navigate.summary', {
  393. organization,
  394. project_platforms: getSelectedProjectPlatforms(location, projects),
  395. });
  396. };
  397. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  398. const widths: number[] = [...this.state.widths];
  399. widths[columnIndex] = nextColumn.width
  400. ? Number(nextColumn.width)
  401. : COL_WIDTH_UNDEFINED;
  402. this.setState({widths});
  403. };
  404. getSortedEventView() {
  405. const {eventView} = this.props;
  406. return eventView.withSorts([
  407. {
  408. field: 'team_key_transaction',
  409. kind: 'desc',
  410. },
  411. ...eventView.sorts,
  412. ]);
  413. }
  414. render() {
  415. const {eventView, organization, location, setError} = this.props;
  416. const {widths, transaction, transactionThreshold} = this.state;
  417. const columnOrder = eventView
  418. .getColumns()
  419. // remove team_key_transactions from the column order as we'll be rendering it
  420. // via a prepended column
  421. .filter(
  422. (col: TableColumn<React.ReactText>) =>
  423. col.name !== 'team_key_transaction' &&
  424. !col.name.startsWith('count_miserable') &&
  425. col.name !== 'project_threshold_config'
  426. )
  427. .map((col: TableColumn<React.ReactText>, i: number) => {
  428. if (typeof widths[i] === 'number') {
  429. return {...col, width: widths[i]};
  430. }
  431. return col;
  432. });
  433. const sortedEventView = this.getSortedEventView();
  434. const columnSortBy = sortedEventView.getSorts();
  435. const prependColumnWidths = ['max-content'];
  436. return (
  437. <GuideAnchor target="performance_table" position="top-start">
  438. <div data-test-id="performance-table">
  439. <MEPConsumer>
  440. {value => {
  441. return (
  442. <DiscoverQuery
  443. eventView={sortedEventView}
  444. orgSlug={organization.slug}
  445. location={location}
  446. setError={error => setError(error?.message)}
  447. referrer="api.performance.landing-table"
  448. transactionName={transaction}
  449. transactionThreshold={transactionThreshold}
  450. queryExtras={getMEPQueryParams(value)}
  451. >
  452. {({pageLinks, isLoading, tableData}) => (
  453. <Fragment>
  454. <VisuallyCompleteWithData
  455. id="PerformanceTable"
  456. hasData={
  457. !isLoading && !!tableData?.data && tableData.data.length > 0
  458. }
  459. isLoading={isLoading}
  460. >
  461. <GridEditable
  462. isLoading={isLoading}
  463. data={tableData ? tableData.data : []}
  464. columnOrder={columnOrder}
  465. columnSortBy={columnSortBy}
  466. grid={{
  467. onResizeColumn: this.handleResizeColumn,
  468. renderHeadCell: this.renderHeadCellWithMeta(
  469. tableData?.meta
  470. ) as any,
  471. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  472. renderPrependColumns: this.renderPrependCellWithData(
  473. tableData
  474. ) as any,
  475. prependColumnWidths,
  476. }}
  477. location={location}
  478. />
  479. </VisuallyCompleteWithData>
  480. <Pagination
  481. pageLinks={pageLinks}
  482. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  483. />
  484. </Fragment>
  485. )}
  486. </DiscoverQuery>
  487. );
  488. }}
  489. </MEPConsumer>
  490. </div>
  491. </GuideAnchor>
  492. );
  493. }
  494. }
  495. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  496. const summaryConditions =
  497. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  498. return <_Table {...props} summaryConditions={summaryConditions} />;
  499. }
  500. // Align the contained IconStar with the IconStar buttons in individual table
  501. // rows, which have 2px padding + 1px border.
  502. const TeamKeyTransactionWrapper = styled('div')`
  503. padding: 3px;
  504. `;
  505. export default Table;