table.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  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, {
  200. organization,
  201. location,
  202. unit: tableMeta.units?.[column.key],
  203. });
  204. const allowActions = [
  205. Actions.ADD,
  206. Actions.EXCLUDE,
  207. Actions.SHOW_GREATER_THAN,
  208. Actions.SHOW_LESS_THAN,
  209. Actions.EDIT_THRESHOLD,
  210. ];
  211. const cellActions = withStaticFilters ? [] : allowActions;
  212. const isUnparameterizedRow = dataRow.transaction === UNPARAMETERIZED_TRANSACTION;
  213. if (field === 'transaction') {
  214. const project = getProject(dataRow, projects);
  215. const projectID = project?.id;
  216. const summaryView = eventView.clone();
  217. if (dataRow['http.method']) {
  218. summaryView.additionalConditions.setFilterValues('http.method', [
  219. dataRow['http.method'] as string,
  220. ]);
  221. }
  222. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  223. if (isUnparameterizedRow && !this.unparameterizedMetricSet) {
  224. this.sendUnparameterizedAnalytic(project);
  225. this.unparameterizedMetricSet = true;
  226. }
  227. const target = isUnparameterizedRow
  228. ? createUnnamedTransactionsDiscoverTarget({
  229. organization,
  230. location,
  231. })
  232. : transactionSummaryRouteWithQuery({
  233. orgSlug: organization.slug,
  234. transaction: String(dataRow.transaction) || '',
  235. query: summaryView.generateQueryStringObject(),
  236. projectID,
  237. });
  238. return (
  239. <CellAction
  240. column={column}
  241. dataRow={dataRow}
  242. handleCellAction={this.handleCellAction(column, dataRow)}
  243. allowActions={cellActions}
  244. >
  245. <Link
  246. to={target}
  247. onClick={this.handleSummaryClick}
  248. style={{display: `block`, width: `100%`}}
  249. >
  250. {rendered}
  251. </Link>
  252. </CellAction>
  253. );
  254. }
  255. if (field.startsWith('team_key_transaction')) {
  256. // don't display per cell actions for team_key_transaction
  257. const project = getProject(dataRow, projects);
  258. const projectMetadata = this.getProjectWithinMetadata(project);
  259. if (isUnparameterizedRow) {
  260. if (projectMetadata.firstEventWithin === '14d') {
  261. return (
  262. <Tooltip
  263. title={t(
  264. 'Transactions are grouped together until we receive enough data to identify parameter patterns.'
  265. )}
  266. >
  267. <UnparameterizedTooltipWrapper data-test-id="unparameterized-indicator">
  268. <LoadingIndicator
  269. mini
  270. size={16}
  271. style={{margin: 0, width: 16, height: 16}}
  272. />
  273. </UnparameterizedTooltipWrapper>
  274. </Tooltip>
  275. );
  276. }
  277. return <span />;
  278. }
  279. return rendered;
  280. }
  281. const fieldName = getAggregateAlias(field);
  282. const value = dataRow[fieldName];
  283. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  284. return (
  285. <Tooltip
  286. title={value.toLocaleString()}
  287. containerDisplayMode="block"
  288. position="right"
  289. >
  290. <CellAction
  291. column={column}
  292. dataRow={dataRow}
  293. handleCellAction={this.handleCellAction(column, dataRow)}
  294. allowActions={cellActions}
  295. >
  296. {rendered}
  297. </CellAction>
  298. </Tooltip>
  299. );
  300. }
  301. return (
  302. <CellAction
  303. column={column}
  304. dataRow={dataRow}
  305. handleCellAction={this.handleCellAction(column, dataRow)}
  306. allowActions={cellActions}
  307. >
  308. {rendered}
  309. </CellAction>
  310. );
  311. }
  312. renderBodyCellWithData = (tableData: TableData | null) => {
  313. return (
  314. column: TableColumn<keyof TableDataRow>,
  315. dataRow: TableDataRow
  316. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  317. };
  318. onSortClick(currentSortKind?: string, currentSortField?: string) {
  319. const {organization} = this.props;
  320. trackAnalytics('performance_views.landingv2.transactions.sort', {
  321. organization,
  322. field: currentSortField,
  323. direction: currentSortKind,
  324. });
  325. }
  326. paginationAnalyticsEvent = (direction: string) => {
  327. const {organization} = this.props;
  328. trackAnalytics('performance_views.landingv3.table_pagination', {
  329. organization,
  330. direction,
  331. });
  332. };
  333. renderHeadCell(
  334. tableMeta: TableData['meta'],
  335. column: TableColumn<keyof TableDataRow>,
  336. title: React.ReactNode
  337. ): React.ReactNode {
  338. const {eventView, location} = this.props;
  339. const align = fieldAlignment(column.name, column.type, tableMeta);
  340. const field = {field: column.name, width: column.width};
  341. const aggregateAliasTableMeta: MetaType = {};
  342. if (tableMeta) {
  343. Object.keys(tableMeta).forEach(key => {
  344. aggregateAliasTableMeta[getAggregateAlias(key)] = tableMeta[key];
  345. });
  346. }
  347. function generateSortLink(): LocationDescriptorObject | undefined {
  348. if (!tableMeta) {
  349. return undefined;
  350. }
  351. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  352. const queryStringObject = nextEventView.generateQueryStringObject();
  353. return {
  354. ...location,
  355. query: {...location.query, sort: queryStringObject.sort},
  356. };
  357. }
  358. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  359. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  360. const currentSortKind = currentSort ? currentSort.kind : undefined;
  361. const currentSortField = currentSort ? currentSort.field : undefined;
  362. const sortLink = (
  363. <SortLink
  364. align={align}
  365. title={title || field.field}
  366. direction={currentSortKind}
  367. canSort={canSort}
  368. generateSortLink={generateSortLink}
  369. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  370. />
  371. );
  372. if (field.field.startsWith('user_misery')) {
  373. return (
  374. <GuideAnchor target="project_transaction_threshold" position="top">
  375. {sortLink}
  376. </GuideAnchor>
  377. );
  378. }
  379. return sortLink;
  380. }
  381. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  382. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  383. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  384. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  385. };
  386. renderPrependCellWithData = (tableData: TableData | null) => {
  387. const {eventView} = this.props;
  388. const teamKeyTransactionColumn = eventView
  389. .getColumns()
  390. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  391. return (isHeader: boolean, dataRow?: any) => {
  392. if (teamKeyTransactionColumn) {
  393. if (isHeader) {
  394. const star = (
  395. <TeamKeyTransactionWrapper>
  396. <IconStar
  397. key="keyTransaction"
  398. color="yellow400"
  399. isSolid
  400. data-test-id="team-key-transaction-header"
  401. />
  402. </TeamKeyTransactionWrapper>
  403. );
  404. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  405. }
  406. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  407. }
  408. return [];
  409. };
  410. };
  411. handleSummaryClick = () => {
  412. const {organization, location, projects} = this.props;
  413. trackAnalytics('performance_views.overview.navigate.summary', {
  414. organization,
  415. project_platforms: getSelectedProjectPlatforms(location, projects),
  416. });
  417. };
  418. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  419. const widths: number[] = [...this.state.widths];
  420. widths[columnIndex] = nextColumn.width
  421. ? Number(nextColumn.width)
  422. : COL_WIDTH_UNDEFINED;
  423. this.setState({widths});
  424. };
  425. getSortedEventView() {
  426. const {eventView} = this.props;
  427. return eventView.withSorts([
  428. {
  429. field: 'team_key_transaction',
  430. kind: 'desc',
  431. },
  432. ...eventView.sorts,
  433. ]);
  434. }
  435. render() {
  436. const {eventView, organization, location, setError} = this.props;
  437. const {widths, transaction, transactionThreshold} = this.state;
  438. const columnOrder = eventView
  439. .getColumns()
  440. // remove team_key_transactions from the column order as we'll be rendering it
  441. // via a prepended column
  442. .filter(
  443. (col: TableColumn<React.ReactText>) =>
  444. col.name !== 'team_key_transaction' &&
  445. !col.name.startsWith('count_miserable') &&
  446. col.name !== 'project_threshold_config'
  447. )
  448. .map((col: TableColumn<React.ReactText>, i: number) => {
  449. if (typeof widths[i] === 'number') {
  450. return {...col, width: widths[i]};
  451. }
  452. return col;
  453. });
  454. const sortedEventView = this.getSortedEventView();
  455. const columnSortBy = sortedEventView.getSorts();
  456. const prependColumnWidths = ['max-content'];
  457. return (
  458. <GuideAnchor target="performance_table" position="top-start">
  459. <div data-test-id="performance-table">
  460. <MEPConsumer>
  461. {value => {
  462. return (
  463. <DiscoverQuery
  464. eventView={sortedEventView}
  465. orgSlug={organization.slug}
  466. location={location}
  467. setError={error => setError(error?.message)}
  468. referrer="api.performance.landing-table"
  469. transactionName={transaction}
  470. transactionThreshold={transactionThreshold}
  471. queryExtras={getMEPQueryParams(value)}
  472. >
  473. {({pageLinks, isLoading, tableData}) => (
  474. <Fragment>
  475. <VisuallyCompleteWithData
  476. id="PerformanceTable"
  477. hasData={
  478. !isLoading && !!tableData?.data && tableData.data.length > 0
  479. }
  480. isLoading={isLoading}
  481. >
  482. <GridEditable
  483. isLoading={isLoading}
  484. data={tableData ? tableData.data : []}
  485. columnOrder={columnOrder}
  486. columnSortBy={columnSortBy}
  487. grid={{
  488. onResizeColumn: this.handleResizeColumn,
  489. renderHeadCell: this.renderHeadCellWithMeta(
  490. tableData?.meta
  491. ) as any,
  492. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  493. renderPrependColumns: this.renderPrependCellWithData(
  494. tableData
  495. ) as any,
  496. prependColumnWidths,
  497. }}
  498. location={location}
  499. />
  500. </VisuallyCompleteWithData>
  501. <Pagination
  502. pageLinks={pageLinks}
  503. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  504. />
  505. </Fragment>
  506. )}
  507. </DiscoverQuery>
  508. );
  509. }}
  510. </MEPConsumer>
  511. </div>
  512. </GuideAnchor>
  513. );
  514. }
  515. }
  516. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  517. const summaryConditions =
  518. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  519. return <_Table {...props} summaryConditions={summaryConditions} />;
  520. }
  521. // Align the contained IconStar with the IconStar buttons in individual table
  522. // rows, which have 2px padding + 1px border.
  523. const TeamKeyTransactionWrapper = styled('div')`
  524. padding: 3px;
  525. `;
  526. const UnparameterizedTooltipWrapper = styled('div')`
  527. display: flex;
  528. align-items: center;
  529. justify-content: center;
  530. `;
  531. export default Table;