table.tsx 20 KB

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