eventsTable.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511
  1. import {Component, Fragment} 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 Tooltip from 'sentry/components/tooltip';
  16. import {t, tct} from 'sentry/locale';
  17. import {IssueAttachment, Organization, Project} from 'sentry/types';
  18. import {defined} from 'sentry/utils';
  19. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  20. import DiscoverQuery, {
  21. TableData,
  22. TableDataRow,
  23. } from 'sentry/utils/discover/discoverQuery';
  24. import EventView, {EventData, 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 parseLinkHeader from 'sentry/utils/parseLinkHeader';
  33. import CellAction, {Actions, updateQuery} from 'sentry/views/eventsV2/table/cellAction';
  34. import {TableColumn} from 'sentry/views/eventsV2/table/types';
  35. import {COLUMN_TITLES} from '../../data';
  36. import {
  37. generateReplayLink,
  38. generateTraceLink,
  39. generateTransactionLink,
  40. normalizeSearchConditions,
  41. } from '../utils';
  42. import OperationSort, {TitleProps} from './operationSort';
  43. export function getProjectID(
  44. eventData: EventData,
  45. projects: Project[]
  46. ): string | undefined {
  47. const projectSlug = (eventData?.project as string) || undefined;
  48. if (typeof projectSlug === undefined) {
  49. return undefined;
  50. }
  51. const project = projects.find(currentProject => currentProject.slug === projectSlug);
  52. if (!project) {
  53. return undefined;
  54. }
  55. return project.id;
  56. }
  57. function OperationTitle({onClick}: TitleProps) {
  58. return (
  59. <div onClick={onClick}>
  60. <span>{t('operation duration')}</span>
  61. <StyledIconQuestion
  62. size="xs"
  63. position="top"
  64. title={t(
  65. `Span durations are summed over the course of an entire transaction. Any overlapping spans are only counted once.`
  66. )}
  67. />
  68. </div>
  69. );
  70. }
  71. type Props = {
  72. eventView: EventView;
  73. location: Location;
  74. organization: Organization;
  75. routes: RouteContextInterface['routes'];
  76. setError: (msg: string | undefined) => void;
  77. transactionName: string;
  78. columnTitles?: string[];
  79. customColumns?: ('attachments' | 'minidump')[];
  80. excludedTags?: string[];
  81. issueId?: string;
  82. projectSlug?: string;
  83. referrer?: string;
  84. showReplayCol?: boolean;
  85. totalEventCount?: string;
  86. };
  87. type State = {
  88. attachments: IssueAttachment[];
  89. hasMinidumps: boolean;
  90. lastFetchedCursor: string;
  91. widths: number[];
  92. };
  93. class EventsTable extends Component<Props, State> {
  94. state: State = {
  95. widths: [],
  96. lastFetchedCursor: '',
  97. attachments: [],
  98. hasMinidumps: false,
  99. };
  100. api = new Client();
  101. replayLinkGenerator = generateReplayLink(this.props.routes);
  102. handleCellAction = (column: TableColumn<keyof TableDataRow>) => {
  103. return (action: Actions, value: React.ReactText) => {
  104. const {eventView, location, organization, excludedTags} = this.props;
  105. trackAnalyticsEvent({
  106. eventKey: 'performance_views.transactionEvents.cellaction',
  107. eventName: 'Performance Views: Transaction Events Tab Cell Action Clicked',
  108. organization_id: parseInt(organization.id, 10),
  109. action,
  110. });
  111. const searchConditions = normalizeSearchConditions(eventView.query);
  112. if (excludedTags) {
  113. excludedTags.forEach(tag => {
  114. searchConditions.removeFilter(tag);
  115. });
  116. }
  117. updateQuery(searchConditions, action, column, value);
  118. browserHistory.push({
  119. pathname: location.pathname,
  120. query: {
  121. ...location.query,
  122. cursor: undefined,
  123. query: searchConditions.formatString(),
  124. },
  125. });
  126. };
  127. };
  128. renderBodyCell(
  129. tableData: TableData | null,
  130. column: TableColumn<keyof TableDataRow>,
  131. dataRow: TableDataRow
  132. ): React.ReactNode {
  133. const {eventView, organization, location, transactionName, projectSlug} = this.props;
  134. if (!tableData || !tableData.meta) {
  135. return dataRow[column.key];
  136. }
  137. const tableMeta = tableData.meta;
  138. const field = String(column.key);
  139. const fieldRenderer = getFieldRenderer(field, tableMeta);
  140. const rendered = fieldRenderer(dataRow, {
  141. organization,
  142. location,
  143. eventView,
  144. projectSlug,
  145. });
  146. const allowActions = [
  147. Actions.ADD,
  148. Actions.EXCLUDE,
  149. Actions.SHOW_GREATER_THAN,
  150. Actions.SHOW_LESS_THAN,
  151. ];
  152. if (['attachments', 'minidump'].includes(field)) {
  153. return rendered;
  154. }
  155. if (field === 'id' || field === 'trace') {
  156. const {issueId} = this.props;
  157. const isIssue: boolean = !!issueId;
  158. let target: LocationDescriptor = {};
  159. // TODO: set referrer properly
  160. if (isIssue && field === 'id') {
  161. target.pathname = `/organizations/${organization.slug}/issues/${issueId}/events/${dataRow.id}/`;
  162. } else {
  163. const generateLink = field === 'id' ? generateTransactionLink : generateTraceLink;
  164. target = generateLink(transactionName)(organization, dataRow, location.query);
  165. }
  166. return (
  167. <CellAction
  168. column={column}
  169. dataRow={dataRow}
  170. handleCellAction={this.handleCellAction(column)}
  171. allowActions={allowActions}
  172. >
  173. <Link to={target}>{rendered}</Link>
  174. </CellAction>
  175. );
  176. }
  177. if (field === 'replayId') {
  178. const target: LocationDescriptor | null = dataRow.replayId
  179. ? this.replayLinkGenerator(organization, dataRow, undefined)
  180. : null;
  181. return (
  182. <CellAction
  183. column={column}
  184. dataRow={dataRow}
  185. handleCellAction={this.handleCellAction(column)}
  186. allowActions={allowActions}
  187. >
  188. {target ? <Link to={target}>{rendered}</Link> : rendered}
  189. </CellAction>
  190. );
  191. }
  192. const fieldName = getAggregateAlias(field);
  193. const value = dataRow[fieldName];
  194. if (tableMeta[fieldName] === 'integer' && defined(value) && value > 999) {
  195. return (
  196. <Tooltip
  197. title={value.toLocaleString()}
  198. containerDisplayMode="block"
  199. position="right"
  200. >
  201. <CellAction
  202. column={column}
  203. dataRow={dataRow}
  204. handleCellAction={this.handleCellAction(column)}
  205. allowActions={allowActions}
  206. >
  207. {rendered}
  208. </CellAction>
  209. </Tooltip>
  210. );
  211. }
  212. return (
  213. <CellAction
  214. column={column}
  215. dataRow={dataRow}
  216. handleCellAction={this.handleCellAction(column)}
  217. allowActions={allowActions}
  218. >
  219. {rendered}
  220. </CellAction>
  221. );
  222. }
  223. renderBodyCellWithData = (tableData: TableData | null) => {
  224. return (
  225. column: TableColumn<keyof TableDataRow>,
  226. dataRow: TableDataRow
  227. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  228. };
  229. onSortClick(currentSortKind?: string, currentSortField?: string) {
  230. const {organization} = this.props;
  231. trackAnalyticsEvent({
  232. eventKey: 'performance_views.transactionEvents.sort',
  233. eventName: 'Performance Views: Transaction Events Tab Sorted',
  234. organization_id: parseInt(organization.id, 10),
  235. field: currentSortField,
  236. direction: currentSortKind,
  237. });
  238. }
  239. renderHeadCell(
  240. tableMeta: TableData['meta'],
  241. column: TableColumn<keyof TableDataRow>,
  242. title: React.ReactNode
  243. ): React.ReactNode {
  244. const {eventView, location} = this.props;
  245. const align = fieldAlignment(column.name, column.type, tableMeta);
  246. const field = {field: column.name, width: column.width};
  247. function generateSortLink(): LocationDescriptorObject | undefined {
  248. if (!tableMeta) {
  249. return undefined;
  250. }
  251. const nextEventView = eventView.sortOnField(field, tableMeta);
  252. const queryStringObject = nextEventView.generateQueryStringObject();
  253. return {
  254. ...location,
  255. query: {...location.query, sort: queryStringObject.sort},
  256. };
  257. }
  258. const currentSort = eventView.sortForField(field, tableMeta);
  259. // 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
  260. const canSort =
  261. field.field !== 'id' &&
  262. field.field !== 'trace' &&
  263. field.field !== 'replayId' &&
  264. field.field !== SPAN_OP_RELATIVE_BREAKDOWN_FIELD &&
  265. isFieldSortable(field, tableMeta);
  266. const currentSortKind = currentSort ? currentSort.kind : undefined;
  267. const currentSortField = currentSort ? currentSort.field : undefined;
  268. if (field.field === SPAN_OP_RELATIVE_BREAKDOWN_FIELD) {
  269. title = (
  270. <OperationSort
  271. title={OperationTitle}
  272. eventView={eventView}
  273. tableMeta={tableMeta}
  274. location={location}
  275. />
  276. );
  277. }
  278. const sortLink = (
  279. <SortLink
  280. align={align}
  281. title={title || field.field}
  282. direction={currentSortKind}
  283. canSort={canSort}
  284. generateSortLink={generateSortLink}
  285. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  286. />
  287. );
  288. return sortLink;
  289. }
  290. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  291. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  292. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  293. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  294. };
  295. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  296. const widths: number[] = [...this.state.widths];
  297. widths[columnIndex] = nextColumn.width
  298. ? Number(nextColumn.width)
  299. : COL_WIDTH_UNDEFINED;
  300. this.setState({...this.state, widths});
  301. };
  302. render() {
  303. const {
  304. eventView,
  305. organization,
  306. location,
  307. setError,
  308. totalEventCount,
  309. referrer,
  310. showReplayCol,
  311. } = this.props;
  312. const totalTransactionsView = eventView.clone();
  313. totalTransactionsView.sorts = [];
  314. totalTransactionsView.fields = [{field: 'count()', width: -1}];
  315. const {widths} = this.state;
  316. const containsSpanOpsBreakdown = eventView
  317. .getColumns()
  318. .find(
  319. (col: TableColumn<React.ReactText>) =>
  320. col.name === SPAN_OP_RELATIVE_BREAKDOWN_FIELD
  321. );
  322. const columnOrder = eventView
  323. .getColumns()
  324. .filter(
  325. (col: TableColumn<React.ReactText>) =>
  326. ((!containsSpanOpsBreakdown || !isSpanOperationBreakdownField(col.name)) &&
  327. col.name !== 'replayId') ||
  328. showReplayCol
  329. )
  330. .map((col: TableColumn<React.ReactText>, i: number) => {
  331. if (typeof widths[i] === 'number') {
  332. return {...col, width: widths[i]};
  333. }
  334. return col;
  335. });
  336. if (
  337. this.props.customColumns?.includes('attachments') &&
  338. this.state.attachments.length
  339. ) {
  340. columnOrder.push({
  341. isSortable: false,
  342. key: 'attachments',
  343. name: 'attachments',
  344. type: 'never',
  345. column: {field: 'attachments', kind: 'field', alias: undefined},
  346. });
  347. }
  348. if (this.props.customColumns?.includes('minidump') && this.state.hasMinidumps) {
  349. columnOrder.push({
  350. isSortable: false,
  351. key: 'minidump',
  352. name: 'minidump',
  353. type: 'never',
  354. column: {field: 'minidump', kind: 'field', alias: undefined},
  355. });
  356. }
  357. const joinCustomData = ({data}: TableData) => {
  358. const attachmentsByEvent = groupBy(this.state.attachments, 'event_id');
  359. data.forEach(event => {
  360. event.attachments = (attachmentsByEvent[event.id] || []) as any;
  361. });
  362. };
  363. const fetchAttachments = async ({data}: TableData, cursor: string) => {
  364. const eventIds = data.map(value => value.id);
  365. const fetchOnlyMinidumps = !this.props.customColumns?.includes('attachments');
  366. const queries: string = [
  367. 'per_page=50',
  368. ...(fetchOnlyMinidumps ? ['types=event.minidump'] : []),
  369. ...eventIds.map(eventId => `event_id=${eventId}`),
  370. ].join('&');
  371. const res: IssueAttachment[] = await this.api.requestPromise(
  372. `/api/0/issues/${this.props.issueId}/attachments/?${queries}`
  373. );
  374. let hasMinidumps = false;
  375. res.forEach(attachment => {
  376. if (attachment.type === 'event.minidump') {
  377. hasMinidumps = true;
  378. }
  379. });
  380. this.setState({
  381. ...this.state,
  382. lastFetchedCursor: cursor,
  383. attachments: res,
  384. hasMinidumps,
  385. });
  386. };
  387. return (
  388. <div data-test-id="events-table">
  389. <DiscoverQuery
  390. eventView={eventView}
  391. orgSlug={organization.slug}
  392. location={location}
  393. setError={error => setError(error?.message)}
  394. referrer={referrer || 'api.performance.transaction-events'}
  395. useEvents
  396. >
  397. {({pageLinks, isLoading: isDiscoverQueryLoading, tableData}) => {
  398. tableData ??= {data: []};
  399. const parsedPageLinks = parseLinkHeader(pageLinks);
  400. const cursor = parsedPageLinks?.next?.cursor;
  401. const shouldFetchAttachments: boolean =
  402. organization.features.includes('event-attachments') &&
  403. !!this.props.issueId &&
  404. !!cursor &&
  405. this.state.lastFetchedCursor !== cursor; // Only fetch on issue details page
  406. let currentEvent = cursor?.split(':')[1] ?? 0;
  407. if (!parsedPageLinks?.next?.results && totalEventCount) {
  408. currentEvent = totalEventCount;
  409. }
  410. const paginationCaption =
  411. totalEventCount && currentEvent
  412. ? tct('Showing [currentEvent] of [totalEventCount] events', {
  413. currentEvent,
  414. totalEventCount,
  415. })
  416. : undefined;
  417. if (shouldFetchAttachments) {
  418. fetchAttachments(tableData, cursor);
  419. }
  420. joinCustomData(tableData);
  421. return (
  422. <Fragment>
  423. <GridEditable
  424. isLoading={isDiscoverQueryLoading || shouldFetchAttachments}
  425. data={tableData?.data ?? []}
  426. columnOrder={columnOrder}
  427. columnSortBy={eventView.getSorts()}
  428. grid={{
  429. onResizeColumn: this.handleResizeColumn,
  430. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  431. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  432. }}
  433. location={location}
  434. />
  435. <Pagination
  436. disabled={isDiscoverQueryLoading}
  437. caption={paginationCaption}
  438. pageLinks={pageLinks}
  439. />
  440. </Fragment>
  441. );
  442. }}
  443. </DiscoverQuery>
  444. </div>
  445. );
  446. }
  447. }
  448. const StyledIconQuestion = styled(QuestionTooltip)`
  449. position: relative;
  450. top: 1px;
  451. left: 4px;
  452. `;
  453. export default EventsTable;