table.tsx 19 KB

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