eventsTable.tsx 18 KB

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