table.tsx 19 KB

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