eventsTable.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. import {Component} from 'react';
  2. import {browserHistory, RouteContextInterface} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location, LocationDescriptor, LocationDescriptorObject} from 'history';
  5. import groupBy from 'lodash/groupBy';
  6. import {Client} from 'sentry/api';
  7. import GridEditable, {
  8. COL_WIDTH_UNDEFINED,
  9. GridColumn,
  10. } from 'sentry/components/gridEditable';
  11. import SortLink from 'sentry/components/gridEditable/sortLink';
  12. import Link from 'sentry/components/links/link';
  13. import Pagination from 'sentry/components/pagination';
  14. import QuestionTooltip from 'sentry/components/questionTooltip';
  15. import ReplayIdCountProvider from 'sentry/components/replays/replayIdCountProvider';
  16. import {Tooltip} from 'sentry/components/tooltip';
  17. import {t, tct} from 'sentry/locale';
  18. import {IssueAttachment, Organization} from 'sentry/types';
  19. import {trackAnalytics} from 'sentry/utils/analytics';
  20. import DiscoverQuery, {
  21. TableData,
  22. TableDataRow,
  23. } from 'sentry/utils/discover/discoverQuery';
  24. import EventView, {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 ViewReplayLink from 'sentry/utils/discover/viewReplayLink';
  33. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  34. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  35. import CellAction, {Actions, updateQuery} from 'sentry/views/discover/table/cellAction';
  36. import {TableColumn} from 'sentry/views/discover/table/types';
  37. import {COLUMN_TITLES} from '../../data';
  38. import {
  39. generateProfileLink,
  40. generateReplayLink,
  41. generateTraceLink,
  42. generateTransactionLink,
  43. normalizeSearchConditions,
  44. } from '../utils';
  45. import OperationSort, {TitleProps} 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. // TODO: set referrer properly
  147. if (isIssue && !isRegressionIssue && field === 'id') {
  148. target.pathname = `/organizations/${organization.slug}/issues/${issueId}/events/${dataRow.id}/`;
  149. } else {
  150. const generateLink = field === 'id' ? generateTransactionLink : generateTraceLink;
  151. target = generateLink(transactionName)(organization, dataRow, location.query);
  152. }
  153. return (
  154. <CellAction
  155. column={column}
  156. dataRow={dataRow}
  157. handleCellAction={this.handleCellAction(column)}
  158. allowActions={allowActions}
  159. >
  160. <Link to={target}>{rendered}</Link>
  161. </CellAction>
  162. );
  163. }
  164. if (field === 'replayId') {
  165. const target: LocationDescriptor | null = dataRow.replayId
  166. ? this.replayLinkGenerator(organization, dataRow, undefined)
  167. : null;
  168. return (
  169. <CellAction
  170. column={column}
  171. dataRow={dataRow}
  172. handleCellAction={this.handleCellAction(column)}
  173. allowActions={allowActions}
  174. >
  175. {target ? (
  176. <ViewReplayLink replayId={dataRow.replayId} to={target}>
  177. {rendered}
  178. </ViewReplayLink>
  179. ) : (
  180. rendered
  181. )}
  182. </CellAction>
  183. );
  184. }
  185. if (field === 'profile.id') {
  186. const target = generateProfileLink()(organization, dataRow, undefined);
  187. const transactionMeetsProfilingRequirements =
  188. typeof dataRow['transaction.duration'] === 'number' &&
  189. dataRow['transaction.duration'] > 20;
  190. return (
  191. <Tooltip
  192. title={
  193. !transactionMeetsProfilingRequirements && !dataRow['profile.id']
  194. ? t('Profiles require a transaction duration of at least 20ms')
  195. : null
  196. }
  197. >
  198. <CellAction
  199. column={column}
  200. dataRow={dataRow}
  201. handleCellAction={this.handleCellAction(column)}
  202. allowActions={allowActions}
  203. >
  204. {target ? <Link to={target}>{rendered}</Link> : rendered}
  205. </CellAction>
  206. </Tooltip>
  207. );
  208. }
  209. const fieldName = getAggregateAlias(field);
  210. const value = dataRow[fieldName];
  211. if (tableMeta[fieldName] === 'integer' && typeof value === 'number' && value > 999) {
  212. return (
  213. <Tooltip
  214. title={value.toLocaleString()}
  215. containerDisplayMode="block"
  216. position="right"
  217. >
  218. <CellAction
  219. column={column}
  220. dataRow={dataRow}
  221. handleCellAction={this.handleCellAction(column)}
  222. allowActions={allowActions}
  223. >
  224. {rendered}
  225. </CellAction>
  226. </Tooltip>
  227. );
  228. }
  229. return (
  230. <CellAction
  231. column={column}
  232. dataRow={dataRow}
  233. handleCellAction={this.handleCellAction(column)}
  234. allowActions={allowActions}
  235. >
  236. {rendered}
  237. </CellAction>
  238. );
  239. }
  240. renderBodyCellWithData = (tableData: TableData | null) => {
  241. return (
  242. column: TableColumn<keyof TableDataRow>,
  243. dataRow: TableDataRow
  244. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  245. };
  246. onSortClick(currentSortKind?: string, currentSortField?: string) {
  247. const {organization} = this.props;
  248. trackAnalytics('performance_views.transactionEvents.sort', {
  249. organization,
  250. field: currentSortField,
  251. direction: currentSortKind,
  252. });
  253. }
  254. renderHeadCell(
  255. tableMeta: TableData['meta'],
  256. column: TableColumn<keyof TableDataRow>,
  257. title: React.ReactNode
  258. ): React.ReactNode {
  259. const {eventView, location} = this.props;
  260. const align = fieldAlignment(column.name, column.type, tableMeta);
  261. const field = {field: column.name, width: column.width};
  262. function generateSortLink(): LocationDescriptorObject | undefined {
  263. if (!tableMeta) {
  264. return undefined;
  265. }
  266. const nextEventView = eventView.sortOnField(field, tableMeta);
  267. const queryStringObject = nextEventView.generateQueryStringObject();
  268. return {
  269. ...location,
  270. query: {...location.query, sort: queryStringObject.sort},
  271. };
  272. }
  273. const currentSort = eventView.sortForField(field, tableMeta);
  274. // 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
  275. const canSort =
  276. field.field !== 'id' &&
  277. field.field !== 'trace' &&
  278. field.field !== 'replayId' &&
  279. field.field !== SPAN_OP_RELATIVE_BREAKDOWN_FIELD &&
  280. isFieldSortable(field, tableMeta);
  281. const currentSortKind = currentSort ? currentSort.kind : undefined;
  282. const currentSortField = currentSort ? currentSort.field : undefined;
  283. if (field.field === SPAN_OP_RELATIVE_BREAKDOWN_FIELD) {
  284. title = (
  285. <OperationSort
  286. title={OperationTitle}
  287. eventView={eventView}
  288. tableMeta={tableMeta}
  289. location={location}
  290. />
  291. );
  292. }
  293. const sortLink = (
  294. <SortLink
  295. align={align}
  296. title={title || field.field}
  297. direction={currentSortKind}
  298. canSort={canSort}
  299. generateSortLink={generateSortLink}
  300. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  301. />
  302. );
  303. return sortLink;
  304. }
  305. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  306. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  307. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  308. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  309. };
  310. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  311. const widths: number[] = [...this.state.widths];
  312. widths[columnIndex] = nextColumn.width
  313. ? Number(nextColumn.width)
  314. : COL_WIDTH_UNDEFINED;
  315. this.setState({...this.state, widths});
  316. };
  317. render() {
  318. const {eventView, organization, location, setError, referrer, isEventLoading} =
  319. this.props;
  320. const totalEventsView = eventView.clone();
  321. totalEventsView.sorts = [];
  322. totalEventsView.fields = [{field: 'count()', width: -1}];
  323. const {widths} = this.state;
  324. const containsSpanOpsBreakdown = eventView
  325. .getColumns()
  326. .find(
  327. (col: TableColumn<React.ReactText>) =>
  328. col.name === SPAN_OP_RELATIVE_BREAKDOWN_FIELD
  329. );
  330. const columnOrder = eventView
  331. .getColumns()
  332. .filter(
  333. (col: TableColumn<React.ReactText>) =>
  334. !containsSpanOpsBreakdown || !isSpanOperationBreakdownField(col.name)
  335. )
  336. .map((col: TableColumn<React.ReactText>, i: number) => {
  337. if (typeof widths[i] === 'number') {
  338. return {...col, width: widths[i]};
  339. }
  340. return col;
  341. });
  342. if (
  343. this.props.customColumns?.includes('attachments') &&
  344. this.state.attachments.length
  345. ) {
  346. columnOrder.push({
  347. isSortable: false,
  348. key: 'attachments',
  349. name: 'attachments',
  350. type: 'never',
  351. column: {field: 'attachments', kind: 'field', alias: undefined},
  352. });
  353. }
  354. if (this.props.customColumns?.includes('minidump') && this.state.hasMinidumps) {
  355. columnOrder.push({
  356. isSortable: false,
  357. key: 'minidump',
  358. name: 'minidump',
  359. type: 'never',
  360. column: {field: 'minidump', kind: 'field', alias: undefined},
  361. });
  362. }
  363. const joinCustomData = ({data}: TableData) => {
  364. const attachmentsByEvent = groupBy(this.state.attachments, 'event_id');
  365. data.forEach(event => {
  366. event.attachments = (attachmentsByEvent[event.id] || []) as any;
  367. });
  368. };
  369. const fetchAttachments = async ({data}: TableData, cursor: string) => {
  370. const eventIds = data.map(value => value.id);
  371. const fetchOnlyMinidumps = !this.props.customColumns?.includes('attachments');
  372. const queries: string = [
  373. 'per_page=50',
  374. ...(fetchOnlyMinidumps ? ['types=event.minidump'] : []),
  375. ...eventIds.map(eventId => `event_id=${eventId}`),
  376. ].join('&');
  377. const res: IssueAttachment[] = await this.api.requestPromise(
  378. `/api/0/issues/${this.props.issueId}/attachments/?${queries}`
  379. );
  380. let hasMinidumps = false;
  381. res.forEach(attachment => {
  382. if (attachment.type === 'event.minidump') {
  383. hasMinidumps = true;
  384. }
  385. });
  386. this.setState({
  387. ...this.state,
  388. lastFetchedCursor: cursor,
  389. attachments: res,
  390. hasMinidumps,
  391. });
  392. };
  393. return (
  394. <div data-test-id="events-table">
  395. <DiscoverQuery
  396. eventView={totalEventsView}
  397. orgSlug={organization.slug}
  398. location={location}
  399. setError={error => setError(error?.message)}
  400. referrer="api.performance.transaction-summary"
  401. cursor="0:0:0"
  402. >
  403. {({isLoading: isTotalEventsLoading, tableData: table}) => {
  404. const totalEventsCount = table?.data[0]?.['count()'] ?? 0;
  405. return (
  406. <DiscoverQuery
  407. eventView={eventView}
  408. orgSlug={organization.slug}
  409. location={location}
  410. setError={error => setError(error?.message)}
  411. referrer={referrer || 'api.performance.transaction-events'}
  412. >
  413. {({pageLinks, isLoading: isDiscoverQueryLoading, tableData}) => {
  414. tableData ??= {data: []};
  415. const pageEventsCount = tableData?.data?.length ?? 0;
  416. const parsedPageLinks = parseLinkHeader(pageLinks);
  417. const cursor = parsedPageLinks?.next?.cursor;
  418. const shouldFetchAttachments: boolean =
  419. organization.features.includes('event-attachments') &&
  420. !!this.props.issueId &&
  421. !!cursor &&
  422. this.state.lastFetchedCursor !== cursor; // Only fetch on issue details page
  423. const paginationCaption =
  424. totalEventsCount && pageEventsCount
  425. ? tct('Showing [pageEventsCount] of [totalEventsCount] events', {
  426. pageEventsCount: pageEventsCount.toLocaleString(),
  427. totalEventsCount: totalEventsCount.toLocaleString(),
  428. })
  429. : undefined;
  430. if (shouldFetchAttachments) {
  431. fetchAttachments(tableData, cursor);
  432. }
  433. joinCustomData(tableData);
  434. const replayIds = tableData.data.map(row => row.replayId);
  435. return (
  436. <ReplayIdCountProvider
  437. organization={organization}
  438. replayIds={replayIds}
  439. >
  440. <VisuallyCompleteWithData
  441. id="TransactionEvents-EventsTable"
  442. hasData={!!tableData?.data?.length}
  443. >
  444. <GridEditable
  445. isLoading={
  446. isTotalEventsLoading ||
  447. isDiscoverQueryLoading ||
  448. shouldFetchAttachments ||
  449. isEventLoading
  450. }
  451. data={tableData?.data ?? []}
  452. columnOrder={columnOrder}
  453. columnSortBy={eventView.getSorts()}
  454. grid={{
  455. onResizeColumn: this.handleResizeColumn,
  456. renderHeadCell: this.renderHeadCellWithMeta(
  457. tableData?.meta
  458. ) as any,
  459. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  460. }}
  461. location={location}
  462. />
  463. </VisuallyCompleteWithData>
  464. <Pagination
  465. disabled={isDiscoverQueryLoading}
  466. caption={paginationCaption}
  467. pageLinks={pageLinks}
  468. />
  469. </ReplayIdCountProvider>
  470. );
  471. }}
  472. </DiscoverQuery>
  473. );
  474. }}
  475. </DiscoverQuery>
  476. </div>
  477. );
  478. }
  479. }
  480. const StyledIconQuestion = styled(QuestionTooltip)`
  481. position: relative;
  482. top: 1px;
  483. left: 4px;
  484. `;
  485. export default EventsTable;