table.tsx 19 KB

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