table.tsx 20 KB

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