table.tsx 21 KB

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