eventsTable.tsx 18 KB

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