eventsTable.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. import type React from 'react';
  2. import {Component, Fragment, type ReactNode} from 'react';
  3. import styled from '@emotion/styled';
  4. import type {Location, LocationDescriptor, LocationDescriptorObject} from 'history';
  5. import groupBy from 'lodash/groupBy';
  6. import {Client} from 'sentry/api';
  7. import {LinkButton} from 'sentry/components/button';
  8. import type {GridColumn} from 'sentry/components/gridEditable';
  9. import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  10. import SortLink from 'sentry/components/gridEditable/sortLink';
  11. import Link from 'sentry/components/links/link';
  12. import Pagination from 'sentry/components/pagination';
  13. import QuestionTooltip from 'sentry/components/questionTooltip';
  14. import {Tooltip} from 'sentry/components/tooltip';
  15. import {IconProfiling} from 'sentry/icons';
  16. import {t, tct} from 'sentry/locale';
  17. import type {IssueAttachment} from 'sentry/types/group';
  18. import type {RouteContextInterface} from 'sentry/types/legacyReactRouter';
  19. import type {Organization} from 'sentry/types/organization';
  20. import {trackAnalytics} from 'sentry/utils/analytics';
  21. import {browserHistory} from 'sentry/utils/browserHistory';
  22. import type {TableData, TableDataRow} from 'sentry/utils/discover/discoverQuery';
  23. import DiscoverQuery from 'sentry/utils/discover/discoverQuery';
  24. import type EventView from 'sentry/utils/discover/eventView';
  25. import {isFieldSortable} from 'sentry/utils/discover/eventView';
  26. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  27. import {
  28. fieldAlignment,
  29. getAggregateAlias,
  30. isSpanOperationBreakdownField,
  31. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  32. } from 'sentry/utils/discover/fields';
  33. import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls';
  34. import ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  35. import {isEmptyObject} from 'sentry/utils/object/isEmptyObject';
  36. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  37. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  38. import CellAction, {Actions, updateQuery} from 'sentry/views/discover/table/cellAction';
  39. import type {TableColumn} from 'sentry/views/discover/table/types';
  40. import type {DomainViewFilters} from 'sentry/views/insights/pages/useFilters';
  41. import {COLUMN_TITLES} from '../../data';
  42. import {TraceViewSources} from '../../newTraceDetails/traceHeader/breadcrumbs';
  43. import Tab from '../tabs';
  44. import {
  45. generateProfileLink,
  46. generateReplayLink,
  47. generateTraceLink,
  48. normalizeSearchConditions,
  49. } from '../utils';
  50. import type {TitleProps} from './operationSort';
  51. import OperationSort from './operationSort';
  52. function shouldRenderColumn(containsSpanOpsBreakdown: boolean, col: string): boolean {
  53. if (containsSpanOpsBreakdown && isSpanOperationBreakdownField(col)) {
  54. return false;
  55. }
  56. if (
  57. col === 'profiler.id' ||
  58. col === 'thread.id' ||
  59. col === 'precise.start_ts' ||
  60. col === 'precise.finish_ts'
  61. ) {
  62. return false;
  63. }
  64. return true;
  65. }
  66. function OperationTitle({onClick}: TitleProps) {
  67. return (
  68. <div onClick={onClick}>
  69. <span>{t('operation duration')}</span>
  70. <StyledIconQuestion
  71. size="xs"
  72. position="top"
  73. title={t(
  74. `Span durations are summed over the course of an entire transaction. Any overlapping spans are only counted once.`
  75. )}
  76. />
  77. </div>
  78. );
  79. }
  80. type Props = {
  81. eventView: EventView;
  82. location: Location;
  83. organization: Organization;
  84. routes: RouteContextInterface['routes'];
  85. setError: (msg: string | undefined) => void;
  86. transactionName: string;
  87. columnTitles?: string[];
  88. customColumns?: ('attachments' | 'minidump')[];
  89. domainViewFilters?: DomainViewFilters;
  90. excludedTags?: string[];
  91. hidePagination?: boolean;
  92. isEventLoading?: boolean;
  93. isRegressionIssue?: boolean;
  94. issueId?: string;
  95. projectSlug?: string;
  96. referrer?: string;
  97. renderTableHeader?: (props: {
  98. isPending: boolean;
  99. pageEventsCount: number;
  100. pageLinks: string | null;
  101. totalEventsCount: ReactNode;
  102. }) => ReactNode;
  103. };
  104. type State = {
  105. attachments: IssueAttachment[];
  106. hasMinidumps: boolean;
  107. lastFetchedCursor: string;
  108. widths: number[];
  109. };
  110. class EventsTable extends Component<Props, State> {
  111. state: State = {
  112. widths: [],
  113. lastFetchedCursor: '',
  114. attachments: [],
  115. hasMinidumps: false,
  116. };
  117. api = new Client();
  118. replayLinkGenerator = generateReplayLink(this.props.routes);
  119. handleCellAction = (column: TableColumn<keyof TableDataRow>) => {
  120. return (action: Actions, value: React.ReactText) => {
  121. const {eventView, location, organization, excludedTags} = this.props;
  122. trackAnalytics('performance_views.transactionEvents.cellaction', {
  123. organization,
  124. action,
  125. });
  126. const searchConditions = normalizeSearchConditions(eventView.query);
  127. if (excludedTags) {
  128. excludedTags.forEach(tag => {
  129. searchConditions.removeFilter(tag);
  130. });
  131. }
  132. updateQuery(searchConditions, action, column, value);
  133. browserHistory.push({
  134. pathname: location.pathname,
  135. query: {
  136. ...location.query,
  137. cursor: undefined,
  138. query: searchConditions.formatString(),
  139. },
  140. });
  141. };
  142. };
  143. renderBodyCell(
  144. tableData: TableData | null,
  145. column: TableColumn<keyof TableDataRow>,
  146. dataRow: TableDataRow
  147. ): React.ReactNode {
  148. const {eventView, organization, location, transactionName, projectSlug} = this.props;
  149. if (!tableData || !tableData.meta) {
  150. return dataRow[column.key];
  151. }
  152. const tableMeta = tableData.meta;
  153. const field = String(column.key);
  154. const fieldRenderer = getFieldRenderer(field, tableMeta);
  155. const rendered = fieldRenderer(dataRow, {
  156. organization,
  157. location,
  158. eventView,
  159. projectSlug,
  160. });
  161. const allowActions = [
  162. Actions.ADD,
  163. Actions.EXCLUDE,
  164. Actions.SHOW_GREATER_THAN,
  165. Actions.SHOW_LESS_THAN,
  166. ];
  167. if (['attachments', 'minidump'].includes(field)) {
  168. return rendered;
  169. }
  170. if (field === 'id' || field === 'trace') {
  171. const {issueId, isRegressionIssue} = this.props;
  172. const isIssue: boolean = !!issueId;
  173. let target: LocationDescriptor = {};
  174. const locationWithTab = {...location, query: {...location.query, tab: Tab.EVENTS}};
  175. // TODO: set referrer properly
  176. if (isIssue && !isRegressionIssue && field === 'id') {
  177. target.pathname = `/organizations/${organization.slug}/issues/${issueId}/events/${dataRow.id}/`;
  178. } else {
  179. if (field === 'id') {
  180. target = generateLinkToEventInTraceView({
  181. traceSlug: dataRow.trace?.toString(),
  182. projectSlug: dataRow['project.name']?.toString(),
  183. eventId: dataRow.id,
  184. timestamp: dataRow.timestamp,
  185. location: locationWithTab,
  186. organization,
  187. transactionName: transactionName,
  188. source: TraceViewSources.PERFORMANCE_TRANSACTION_SUMMARY,
  189. view: this.props.domainViewFilters?.view,
  190. });
  191. } else {
  192. target = generateTraceLink(transactionName, this.props.domainViewFilters?.view)(
  193. organization,
  194. dataRow,
  195. locationWithTab
  196. );
  197. }
  198. }
  199. return (
  200. <CellAction
  201. column={column}
  202. dataRow={dataRow}
  203. handleCellAction={this.handleCellAction(column)}
  204. allowActions={allowActions}
  205. >
  206. <Link to={target}>{rendered}</Link>
  207. </CellAction>
  208. );
  209. }
  210. if (field === 'replayId') {
  211. const target: LocationDescriptor | null = dataRow.replayId
  212. ? this.replayLinkGenerator(organization, dataRow, undefined)
  213. : null;
  214. return (
  215. <CellAction
  216. column={column}
  217. dataRow={dataRow}
  218. handleCellAction={this.handleCellAction(column)}
  219. allowActions={allowActions}
  220. >
  221. {target ? (
  222. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  223. {rendered}
  224. </ViewReplayLink>
  225. ) : (
  226. rendered
  227. )}
  228. </CellAction>
  229. );
  230. }
  231. if (field === 'profile.id') {
  232. const target = generateProfileLink()(organization, dataRow, undefined);
  233. const transactionMeetsProfilingRequirements =
  234. typeof dataRow['transaction.duration'] === 'number' &&
  235. dataRow['transaction.duration'] > 20;
  236. return (
  237. <Tooltip
  238. title={
  239. !transactionMeetsProfilingRequirements && !dataRow['profile.id']
  240. ? t('Profiles require a transaction duration of at least 20ms')
  241. : null
  242. }
  243. >
  244. <CellAction
  245. column={column}
  246. dataRow={dataRow}
  247. handleCellAction={this.handleCellAction(column)}
  248. allowActions={allowActions}
  249. >
  250. <div>
  251. <LinkButton
  252. disabled={!target || isEmptyObject(target)}
  253. to={target || {}}
  254. size="xs"
  255. >
  256. <IconProfiling size="xs" />
  257. </LinkButton>
  258. </div>
  259. </CellAction>
  260. </Tooltip>
  261. );
  262. }
  263. const fieldName = getAggregateAlias(field);
  264. const value = dataRow[fieldName];
  265. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  266. return (
  267. <Tooltip
  268. title={value.toLocaleString()}
  269. containerDisplayMode="block"
  270. position="right"
  271. >
  272. <CellAction
  273. column={column}
  274. dataRow={dataRow}
  275. handleCellAction={this.handleCellAction(column)}
  276. allowActions={allowActions}
  277. >
  278. {rendered}
  279. </CellAction>
  280. </Tooltip>
  281. );
  282. }
  283. return (
  284. <CellAction
  285. column={column}
  286. dataRow={dataRow}
  287. handleCellAction={this.handleCellAction(column)}
  288. allowActions={allowActions}
  289. >
  290. {rendered}
  291. </CellAction>
  292. );
  293. }
  294. renderBodyCellWithData = (tableData: TableData | null) => {
  295. return (
  296. column: TableColumn<keyof TableDataRow>,
  297. dataRow: TableDataRow
  298. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  299. };
  300. onSortClick(currentSortKind?: string, currentSortField?: string) {
  301. const {organization} = this.props;
  302. trackAnalytics('performance_views.transactionEvents.sort', {
  303. organization,
  304. field: currentSortField,
  305. direction: currentSortKind,
  306. });
  307. }
  308. renderHeadCell(
  309. tableMeta: TableData['meta'],
  310. column: TableColumn<keyof TableDataRow>,
  311. title: React.ReactNode
  312. ): React.ReactNode {
  313. const {eventView, location} = this.props;
  314. const align = fieldAlignment(column.name, column.type, tableMeta);
  315. const field = {field: column.name, width: column.width};
  316. function generateSortLink(): LocationDescriptorObject | undefined {
  317. if (!tableMeta) {
  318. return undefined;
  319. }
  320. const nextEventView = eventView.sortOnField(field, tableMeta);
  321. const queryStringObject = nextEventView.generateQueryStringObject();
  322. return {
  323. ...location,
  324. query: {...location.query, sort: queryStringObject.sort},
  325. };
  326. }
  327. const currentSort = eventView.sortForField(field, tableMeta);
  328. // EventId, TraceId, and ReplayId are technically sortable but we don't want to sort them here since sorting by a uuid value doesn't make sense
  329. const canSort =
  330. field.field !== 'id' &&
  331. field.field !== 'trace' &&
  332. field.field !== 'replayId' &&
  333. field.field !== SPAN_OP_RELATIVE_BREAKDOWN_FIELD &&
  334. isFieldSortable(field, tableMeta);
  335. const currentSortKind = currentSort ? currentSort.kind : undefined;
  336. const currentSortField = currentSort ? currentSort.field : undefined;
  337. if (field.field === SPAN_OP_RELATIVE_BREAKDOWN_FIELD) {
  338. title = (
  339. <OperationSort
  340. title={OperationTitle}
  341. eventView={eventView}
  342. tableMeta={tableMeta}
  343. location={location}
  344. />
  345. );
  346. }
  347. const sortLink = (
  348. <SortLink
  349. align={align}
  350. title={title || field.field}
  351. direction={currentSortKind}
  352. canSort={canSort}
  353. generateSortLink={generateSortLink}
  354. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  355. />
  356. );
  357. return sortLink;
  358. }
  359. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  360. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  361. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  362. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  363. };
  364. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  365. const widths: number[] = [...this.state.widths];
  366. widths[columnIndex] = nextColumn.width
  367. ? Number(nextColumn.width)
  368. : COL_WIDTH_UNDEFINED;
  369. this.setState({...this.state, widths});
  370. };
  371. render() {
  372. const {eventView, organization, location, setError, referrer, isEventLoading} =
  373. this.props;
  374. const totalEventsView = eventView.clone();
  375. totalEventsView.sorts = [];
  376. totalEventsView.fields = [{field: 'count()', width: -1}];
  377. const {widths} = this.state;
  378. const containsSpanOpsBreakdown = !!eventView
  379. .getColumns()
  380. .find(
  381. (col: TableColumn<React.ReactText>) =>
  382. col.name === SPAN_OP_RELATIVE_BREAKDOWN_FIELD
  383. );
  384. const columnOrder = eventView
  385. .getColumns()
  386. .filter((col: TableColumn<React.ReactText>) =>
  387. shouldRenderColumn(containsSpanOpsBreakdown, col.name)
  388. )
  389. .map((col: TableColumn<React.ReactText>, i: number) => {
  390. if (typeof widths[i] === 'number') {
  391. return {...col, width: widths[i]};
  392. }
  393. return col;
  394. });
  395. if (
  396. this.props.customColumns?.includes('attachments') &&
  397. this.state.attachments.length
  398. ) {
  399. columnOrder.push({
  400. isSortable: false,
  401. key: 'attachments',
  402. name: 'attachments',
  403. type: 'never',
  404. column: {field: 'attachments', kind: 'field', alias: undefined},
  405. });
  406. }
  407. if (this.props.customColumns?.includes('minidump') && this.state.hasMinidumps) {
  408. columnOrder.push({
  409. isSortable: false,
  410. key: 'minidump',
  411. name: 'minidump',
  412. type: 'never',
  413. column: {field: 'minidump', kind: 'field', alias: undefined},
  414. });
  415. }
  416. const joinCustomData = ({data}: TableData) => {
  417. const attachmentsByEvent = groupBy(this.state.attachments, 'event_id');
  418. data.forEach(event => {
  419. event.attachments = (attachmentsByEvent[event.id] || []) as any;
  420. });
  421. };
  422. const fetchAttachments = async ({data}: TableData, cursor: string) => {
  423. const eventIds = data.map(value => value.id);
  424. const fetchOnlyMinidumps = !this.props.customColumns?.includes('attachments');
  425. const queries: string = [
  426. 'per_page=50',
  427. ...(fetchOnlyMinidumps ? ['types=event.minidump'] : []),
  428. ...eventIds.map(eventId => `event_id=${eventId}`),
  429. ].join('&');
  430. const res: IssueAttachment[] = await this.api.requestPromise(
  431. `/api/0/issues/${this.props.issueId}/attachments/?${queries}`
  432. );
  433. let hasMinidumps = false;
  434. res.forEach(attachment => {
  435. if (attachment.type === 'event.minidump') {
  436. hasMinidumps = true;
  437. }
  438. });
  439. this.setState({
  440. ...this.state,
  441. lastFetchedCursor: cursor,
  442. attachments: res,
  443. hasMinidumps,
  444. });
  445. };
  446. return (
  447. <div data-test-id="events-table">
  448. <DiscoverQuery
  449. eventView={totalEventsView}
  450. orgSlug={organization.slug}
  451. location={location}
  452. setError={error => setError(error?.message)}
  453. referrer="api.performance.transaction-summary"
  454. cursor="0:0:0"
  455. >
  456. {({isLoading: isTotalEventsLoading, tableData: table}) => {
  457. const totalEventsCount = table?.data[0]?.['count()'] ?? 0;
  458. return (
  459. <DiscoverQuery
  460. eventView={eventView}
  461. orgSlug={organization.slug}
  462. location={location}
  463. setError={error => setError(error?.message)}
  464. referrer={referrer || 'api.performance.transaction-events'}
  465. >
  466. {({pageLinks, isLoading: isDiscoverQueryLoading, tableData}) => {
  467. tableData ??= {data: []};
  468. const pageEventsCount = tableData?.data?.length ?? 0;
  469. const parsedPageLinks = parseLinkHeader(pageLinks);
  470. const cursor = parsedPageLinks?.next?.cursor;
  471. const shouldFetchAttachments: boolean =
  472. organization.features.includes('event-attachments') &&
  473. !!this.props.issueId &&
  474. !!cursor &&
  475. this.state.lastFetchedCursor !== cursor; // Only fetch on issue details page
  476. const paginationCaption =
  477. totalEventsCount && pageEventsCount
  478. ? tct('Showing [pageEventsCount] of [totalEventsCount] events', {
  479. pageEventsCount: pageEventsCount.toLocaleString(),
  480. totalEventsCount: totalEventsCount.toLocaleString(),
  481. })
  482. : undefined;
  483. if (shouldFetchAttachments) {
  484. fetchAttachments(tableData, cursor);
  485. }
  486. joinCustomData(tableData);
  487. return (
  488. <Fragment>
  489. <VisuallyCompleteWithData
  490. id="TransactionEvents-EventsTable"
  491. hasData={!!tableData?.data?.length}
  492. >
  493. {this.props.renderTableHeader
  494. ? this.props.renderTableHeader({
  495. isPending: isDiscoverQueryLoading,
  496. pageLinks,
  497. pageEventsCount,
  498. totalEventsCount,
  499. })
  500. : null}
  501. <GridEditable
  502. isLoading={
  503. isTotalEventsLoading ||
  504. isDiscoverQueryLoading ||
  505. shouldFetchAttachments ||
  506. isEventLoading
  507. }
  508. data={tableData?.data ?? []}
  509. columnOrder={columnOrder}
  510. columnSortBy={eventView.getSorts()}
  511. grid={{
  512. onResizeColumn: this.handleResizeColumn,
  513. renderHeadCell: this.renderHeadCellWithMeta(
  514. tableData?.meta
  515. ) as any,
  516. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  517. }}
  518. />
  519. </VisuallyCompleteWithData>
  520. {this.props.hidePagination ? null : (
  521. <Pagination
  522. disabled={isDiscoverQueryLoading}
  523. caption={paginationCaption}
  524. pageLinks={pageLinks}
  525. />
  526. )}
  527. </Fragment>
  528. );
  529. }}
  530. </DiscoverQuery>
  531. );
  532. }}
  533. </DiscoverQuery>
  534. </div>
  535. );
  536. }
  537. }
  538. const StyledIconQuestion = styled(QuestionTooltip)`
  539. position: relative;
  540. top: 1px;
  541. left: 4px;
  542. `;
  543. export default EventsTable;