eventsTable.tsx 17 KB

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