eventsTable.tsx 17 KB

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