eventsTable.tsx 17 KB

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