eventsTable.tsx 17 KB

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