eventsTable.tsx 19 KB

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