eventsTable.tsx 17 KB

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