eventsTable.tsx 18 KB

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