table.tsx 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  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. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  186. transactionThreshold={project_threshold[1]}
  187. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  188. transactionThresholdMetric={project_threshold[0]}
  189. onApply={(threshold, metric) => {
  190. if (
  191. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  192. threshold !== project_threshold[1] ||
  193. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  194. metric !== project_threshold[0]
  195. ) {
  196. this.setState({
  197. transaction: transactionName,
  198. transactionThreshold: threshold,
  199. transactionThresholdMetric: metric,
  200. });
  201. }
  202. addSuccessMessage(
  203. tct('[transactionName] updated successfully', {
  204. transactionName,
  205. })
  206. );
  207. }}
  208. />
  209. ),
  210. {modalCss, closeEvents: 'escape-key'}
  211. );
  212. return;
  213. }
  214. const searchConditions = normalizeSearchConditionsWithTransactionName(
  215. eventView.query
  216. );
  217. updateQuery(searchConditions, action, column, value);
  218. browserHistory.push({
  219. pathname: location.pathname,
  220. query: {
  221. ...location.query,
  222. cursor: undefined,
  223. query: searchConditions.formatString(),
  224. },
  225. });
  226. };
  227. };
  228. renderBodyCell(
  229. tableData: TableData | null,
  230. column: TableColumn<keyof TableDataRow>,
  231. dataRow: TableDataRow
  232. ): React.ReactNode {
  233. const {eventView, organization, projects, location, withStaticFilters} = this.props;
  234. if (!tableData || !tableData.meta) {
  235. return dataRow[column.key];
  236. }
  237. const tableMeta = tableData.meta;
  238. const field = String(column.key);
  239. const fieldRenderer = getFieldRenderer(field, tableMeta, false);
  240. const rendered = fieldRenderer(dataRow, {
  241. organization,
  242. location,
  243. unit: tableMeta.units?.[column.key],
  244. });
  245. const allowActions = [
  246. Actions.ADD,
  247. Actions.EXCLUDE,
  248. Actions.SHOW_GREATER_THAN,
  249. Actions.SHOW_LESS_THAN,
  250. Actions.EDIT_THRESHOLD,
  251. ];
  252. const cellActions = withStaticFilters ? [] : allowActions;
  253. const isUnparameterizedRow = dataRow.transaction === UNPARAMETERIZED_TRANSACTION;
  254. if (field === 'transaction') {
  255. const project = getProject(dataRow, projects);
  256. const projectID = project?.id;
  257. const summaryView = eventView.clone();
  258. if (dataRow['http.method']) {
  259. summaryView.additionalConditions.setFilterValues('http.method', [
  260. dataRow['http.method'] as string,
  261. ]);
  262. }
  263. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  264. if (isUnparameterizedRow && !this.unparameterizedMetricSet) {
  265. this.sendUnparameterizedAnalytic(project);
  266. this.unparameterizedMetricSet = true;
  267. }
  268. const {isInDomainView, view} = this.props.domainViewFilters ?? {};
  269. const target = isUnparameterizedRow
  270. ? createUnnamedTransactionsDiscoverTarget({
  271. organization,
  272. location,
  273. })
  274. : transactionSummaryRouteWithQuery({
  275. orgSlug: organization.slug,
  276. transaction: String(dataRow.transaction) || '',
  277. query: summaryView.generateQueryStringObject(),
  278. projectID,
  279. view: (isInDomainView && view) || undefined,
  280. });
  281. return (
  282. <CellAction
  283. column={column}
  284. dataRow={dataRow}
  285. handleCellAction={this.handleCellAction(column, dataRow)}
  286. allowActions={cellActions}
  287. >
  288. <Link
  289. to={target}
  290. onClick={this.handleSummaryClick}
  291. style={{display: `block`, width: `100%`}}
  292. >
  293. {rendered}
  294. </Link>
  295. </CellAction>
  296. );
  297. }
  298. if (field.startsWith('team_key_transaction')) {
  299. // don't display per cell actions for team_key_transaction
  300. const project = getProject(dataRow, projects);
  301. const projectMetadata = this.getProjectWithinMetadata(project);
  302. if (isUnparameterizedRow) {
  303. if (projectMetadata.firstEventWithin === '14d') {
  304. return (
  305. <Tooltip
  306. title={t(
  307. 'Transactions are grouped together until we receive enough data to identify parameter patterns.'
  308. )}
  309. >
  310. <UnparameterizedTooltipWrapper data-test-id="unparameterized-indicator">
  311. <LoadingIndicator
  312. mini
  313. size={16}
  314. style={{margin: 0, width: 16, height: 16}}
  315. />
  316. </UnparameterizedTooltipWrapper>
  317. </Tooltip>
  318. );
  319. }
  320. return <span />;
  321. }
  322. return rendered;
  323. }
  324. const fieldName = getAggregateAlias(field);
  325. const value = dataRow[fieldName];
  326. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  327. return (
  328. <Tooltip
  329. title={value.toLocaleString()}
  330. containerDisplayMode="block"
  331. position="right"
  332. >
  333. <CellAction
  334. column={column}
  335. dataRow={dataRow}
  336. handleCellAction={this.handleCellAction(column, dataRow)}
  337. allowActions={cellActions}
  338. >
  339. {rendered}
  340. </CellAction>
  341. </Tooltip>
  342. );
  343. }
  344. return (
  345. <CellAction
  346. column={column}
  347. dataRow={dataRow}
  348. handleCellAction={this.handleCellAction(column, dataRow)}
  349. allowActions={cellActions}
  350. >
  351. {rendered}
  352. </CellAction>
  353. );
  354. }
  355. renderBodyCellWithData = (tableData: TableData | null) => {
  356. return (
  357. column: TableColumn<keyof TableDataRow>,
  358. dataRow: TableDataRow
  359. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  360. };
  361. onSortClick(currentSortKind?: string, currentSortField?: string) {
  362. const {organization} = this.props;
  363. trackAnalytics('performance_views.landingv2.transactions.sort', {
  364. organization,
  365. field: currentSortField,
  366. direction: currentSortKind,
  367. });
  368. }
  369. paginationAnalyticsEvent = (direction: string) => {
  370. const {organization} = this.props;
  371. trackAnalytics('performance_views.landingv3.table_pagination', {
  372. organization,
  373. direction,
  374. });
  375. };
  376. renderHeadCell(
  377. tableMeta: TableData['meta'],
  378. column: TableColumn<keyof TableDataRow>,
  379. title: ColumnTitle
  380. ): React.ReactNode {
  381. const {eventView, location} = this.props;
  382. const align = fieldAlignment(column.name, column.type, tableMeta);
  383. const field = {field: column.name, width: column.width};
  384. const aggregateAliasTableMeta: MetaType = {};
  385. if (tableMeta) {
  386. Object.keys(tableMeta).forEach(key => {
  387. aggregateAliasTableMeta[getAggregateAlias(key)] = tableMeta[key];
  388. });
  389. }
  390. function generateSortLink(): LocationDescriptorObject | undefined {
  391. if (!tableMeta) {
  392. return undefined;
  393. }
  394. const nextEventView = eventView.sortOnField(field, aggregateAliasTableMeta);
  395. const queryStringObject = nextEventView.generateQueryStringObject();
  396. return {
  397. ...location,
  398. query: {...location.query, sort: queryStringObject.sort},
  399. };
  400. }
  401. const currentSort = eventView.sortForField(field, aggregateAliasTableMeta);
  402. const canSort = isFieldSortable(field, aggregateAliasTableMeta);
  403. const currentSortKind = currentSort ? currentSort.kind : undefined;
  404. const currentSortField = currentSort ? currentSort.field : undefined;
  405. const sortLink = (
  406. <SortLink
  407. align={align}
  408. title={title.title || field.field}
  409. direction={currentSortKind}
  410. canSort={canSort}
  411. generateSortLink={generateSortLink}
  412. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  413. />
  414. );
  415. if (field.field.startsWith('user_misery')) {
  416. if (title.tooltip) {
  417. return (
  418. <GuideAnchor target="project_transaction_threshold" position="top">
  419. <Tooltip isHoverable title={title.tooltip} showUnderline>
  420. {sortLink}
  421. </Tooltip>
  422. </GuideAnchor>
  423. );
  424. }
  425. return (
  426. <GuideAnchor target="project_transaction_threshold" position="top">
  427. {sortLink}
  428. </GuideAnchor>
  429. );
  430. }
  431. if (!title.tooltip) {
  432. return sortLink;
  433. }
  434. return (
  435. <Tooltip isHoverable title={title.tooltip} showUnderline>
  436. {sortLink}
  437. </Tooltip>
  438. );
  439. }
  440. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  441. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES_OPTIONAL_TOOLTIP;
  442. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  443. this.renderHeadCell(tableMeta, column, columnTitles[index]!);
  444. };
  445. renderPrependCellWithData = (tableData: TableData | null) => {
  446. const {eventView} = this.props;
  447. const teamKeyTransactionColumn = eventView
  448. .getColumns()
  449. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  450. return (isHeader: boolean, dataRow?: any) => {
  451. if (teamKeyTransactionColumn) {
  452. if (isHeader) {
  453. const star = (
  454. <TeamKeyTransactionWrapper>
  455. <IconStar
  456. key="keyTransaction"
  457. color="yellow300"
  458. isSolid
  459. data-test-id="team-key-transaction-header"
  460. />
  461. </TeamKeyTransactionWrapper>
  462. );
  463. return [
  464. this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, {title: star}),
  465. ];
  466. }
  467. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  468. }
  469. return [];
  470. };
  471. };
  472. handleSummaryClick = () => {
  473. const {organization, location, projects} = this.props;
  474. trackAnalytics('performance_views.overview.navigate.summary', {
  475. organization,
  476. project_platforms: getSelectedProjectPlatforms(location, projects),
  477. });
  478. };
  479. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  480. const widths: number[] = [...this.state.widths];
  481. widths[columnIndex] = nextColumn.width
  482. ? Number(nextColumn.width)
  483. : COL_WIDTH_UNDEFINED;
  484. this.setState({widths});
  485. };
  486. getSortedEventView() {
  487. const {eventView} = this.props;
  488. return eventView.withSorts([
  489. {
  490. field: 'team_key_transaction',
  491. kind: 'desc',
  492. },
  493. ...eventView.sorts,
  494. ]);
  495. }
  496. render() {
  497. const {eventView, organization, location, setError} = this.props;
  498. const {widths, transaction, transactionThreshold} = this.state;
  499. const columnOrder = eventView
  500. .getColumns()
  501. // remove team_key_transactions from the column order as we'll be rendering it
  502. // via a prepended column
  503. .filter(
  504. (col: TableColumn<React.ReactText>) =>
  505. col.name !== 'team_key_transaction' &&
  506. !col.name.startsWith('count_miserable') &&
  507. col.name !== 'project_threshold_config'
  508. )
  509. .map((col: TableColumn<React.ReactText>, i: number) => {
  510. if (typeof widths[i] === 'number') {
  511. return {...col, width: widths[i]};
  512. }
  513. return col;
  514. });
  515. const sortedEventView = this.getSortedEventView();
  516. const columnSortBy = sortedEventView.getSorts();
  517. const prependColumnWidths = ['max-content'];
  518. return (
  519. <GuideAnchor target="performance_table" position="top-start">
  520. <div data-test-id="performance-table">
  521. <MEPConsumer>
  522. {value => {
  523. return (
  524. <DiscoverQuery
  525. eventView={sortedEventView}
  526. orgSlug={organization.slug}
  527. location={location}
  528. setError={error => setError(error?.message)}
  529. referrer="api.performance.landing-table"
  530. transactionName={transaction}
  531. transactionThreshold={transactionThreshold}
  532. queryExtras={getMEPQueryParams(value)}
  533. >
  534. {({pageLinks, isLoading, tableData}) => (
  535. <TrackHasDataAnalytics isLoading={isLoading} tableData={tableData}>
  536. <VisuallyCompleteWithData
  537. id="PerformanceTable"
  538. hasData={
  539. !isLoading && !!tableData?.data && tableData.data.length > 0
  540. }
  541. isLoading={isLoading}
  542. >
  543. <GridEditable
  544. isLoading={isLoading}
  545. data={tableData ? tableData.data : []}
  546. columnOrder={columnOrder}
  547. columnSortBy={columnSortBy}
  548. bodyStyle={{overflow: 'visible'}}
  549. grid={{
  550. onResizeColumn: this.handleResizeColumn,
  551. renderHeadCell: this.renderHeadCellWithMeta(
  552. tableData?.meta
  553. ) as any,
  554. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  555. renderPrependColumns: this.renderPrependCellWithData(
  556. tableData
  557. ) as any,
  558. prependColumnWidths,
  559. }}
  560. />
  561. </VisuallyCompleteWithData>
  562. <Pagination
  563. pageLinks={pageLinks}
  564. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  565. />
  566. </TrackHasDataAnalytics>
  567. )}
  568. </DiscoverQuery>
  569. );
  570. }}
  571. </MEPConsumer>
  572. </div>
  573. </GuideAnchor>
  574. );
  575. }
  576. }
  577. function Table(props: Omit<Props, 'summaryConditions'> & {summaryConditions?: string}) {
  578. const summaryConditions =
  579. props.summaryConditions ?? props.eventView.getQueryWithAdditionalConditions();
  580. const domainViewFilters = useDomainViewFilters();
  581. return (
  582. <_Table
  583. {...props}
  584. summaryConditions={summaryConditions}
  585. domainViewFilters={domainViewFilters}
  586. />
  587. );
  588. }
  589. // Align the contained IconStar with the IconStar buttons in individual table
  590. // rows, which have 2px padding + 1px border.
  591. const TeamKeyTransactionWrapper = styled('div')`
  592. padding: 3px;
  593. `;
  594. const UnparameterizedTooltipWrapper = styled('div')`
  595. display: flex;
  596. align-items: center;
  597. justify-content: center;
  598. `;
  599. export default Table;