eventsTable.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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. projectId?: string;
  83. referrer?: string;
  84. totalEventCount?: string;
  85. };
  86. type State = {
  87. attachments: IssueAttachment[];
  88. hasMinidumps: boolean;
  89. lastFetchedCursor: string;
  90. widths: number[];
  91. };
  92. class EventsTable extends Component<Props, State> {
  93. state: State = {
  94. widths: [],
  95. lastFetchedCursor: '',
  96. attachments: [],
  97. hasMinidumps: false,
  98. };
  99. api = new Client();
  100. replayLinkGenerator = generateReplayLink(this.props.routes);
  101. handleCellAction = (column: TableColumn<keyof TableDataRow>) => {
  102. return (action: Actions, value: React.ReactText) => {
  103. const {eventView, location, organization, excludedTags} = this.props;
  104. trackAnalyticsEvent({
  105. eventKey: 'performance_views.transactionEvents.cellaction',
  106. eventName: 'Performance Views: Transaction Events Tab Cell Action Clicked',
  107. organization_id: parseInt(organization.id, 10),
  108. action,
  109. });
  110. const searchConditions = normalizeSearchConditions(eventView.query);
  111. if (excludedTags) {
  112. excludedTags.forEach(tag => {
  113. searchConditions.removeFilter(tag);
  114. });
  115. }
  116. updateQuery(searchConditions, action, column, value);
  117. browserHistory.push({
  118. pathname: location.pathname,
  119. query: {
  120. ...location.query,
  121. cursor: undefined,
  122. query: searchConditions.formatString(),
  123. },
  124. });
  125. };
  126. };
  127. renderBodyCell(
  128. tableData: TableData | null,
  129. column: TableColumn<keyof TableDataRow>,
  130. dataRow: TableDataRow
  131. ): React.ReactNode {
  132. const {eventView, organization, location, transactionName, projectId} = this.props;
  133. if (!tableData || !tableData.meta) {
  134. return dataRow[column.key];
  135. }
  136. const tableMeta = tableData.meta;
  137. const field = String(column.key);
  138. const fieldRenderer = getFieldRenderer(field, tableMeta);
  139. const rendered = fieldRenderer(dataRow, {
  140. organization,
  141. location,
  142. eventView,
  143. projectId,
  144. });
  145. const allowActions = [
  146. Actions.ADD,
  147. Actions.EXCLUDE,
  148. Actions.SHOW_GREATER_THAN,
  149. Actions.SHOW_LESS_THAN,
  150. ];
  151. if (['attachments', 'minidump'].includes(field)) {
  152. return rendered;
  153. }
  154. if (field === 'id' || field === 'trace') {
  155. const {issueId} = this.props;
  156. const isIssue: boolean = !!issueId;
  157. let target: LocationDescriptor = {};
  158. if (isIssue && field === 'id') {
  159. target.pathname = `/organizations/${organization.slug}/issues/${issueId}/events/${dataRow.id}/`;
  160. target.search = '?referrer=events-table';
  161. } else {
  162. const generateLink = field === 'id' ? generateTransactionLink : generateTraceLink;
  163. target = generateLink(transactionName)(organization, dataRow, location.query);
  164. // TODO: add referrer
  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 {eventView, organization, location, setError, totalEventCount, referrer} =
  304. this.props;
  305. const totalTransactionsView = eventView.clone();
  306. totalTransactionsView.sorts = [];
  307. totalTransactionsView.fields = [{field: 'count()', width: -1}];
  308. const {widths} = this.state;
  309. const containsSpanOpsBreakdown = eventView
  310. .getColumns()
  311. .find(
  312. (col: TableColumn<React.ReactText>) =>
  313. col.name === SPAN_OP_RELATIVE_BREAKDOWN_FIELD
  314. );
  315. const columnOrder = eventView
  316. .getColumns()
  317. .filter(
  318. (col: TableColumn<React.ReactText>) =>
  319. !containsSpanOpsBreakdown || !isSpanOperationBreakdownField(col.name)
  320. )
  321. .map((col: TableColumn<React.ReactText>, i: number) => {
  322. if (typeof widths[i] === 'number') {
  323. return {...col, width: widths[i]};
  324. }
  325. return col;
  326. });
  327. if (
  328. this.props.customColumns?.includes('attachments') &&
  329. this.state.attachments.length
  330. ) {
  331. columnOrder.push({
  332. isSortable: false,
  333. key: 'attachments',
  334. name: 'attachments',
  335. type: 'never',
  336. column: {field: 'attachments', kind: 'field', alias: undefined},
  337. });
  338. }
  339. if (this.props.customColumns?.includes('minidump') && this.state.hasMinidumps) {
  340. columnOrder.push({
  341. isSortable: false,
  342. key: 'minidump',
  343. name: 'minidump',
  344. type: 'never',
  345. column: {field: 'minidump', kind: 'field', alias: undefined},
  346. });
  347. }
  348. const joinCustomData = ({data}: TableData) => {
  349. const attachmentsByEvent = groupBy(this.state.attachments, 'event_id');
  350. data.forEach(event => {
  351. event.attachments = (attachmentsByEvent[event.id] || []) as any;
  352. });
  353. };
  354. const fetchAttachments = async ({data}: TableData, cursor: string) => {
  355. const eventIds = data.map(value => value.id);
  356. const fetchOnlyMinidumps = !this.props.customColumns?.includes('attachments');
  357. const queries: string = [
  358. 'per_page=50',
  359. ...(fetchOnlyMinidumps ? ['types=event.minidump'] : []),
  360. ...eventIds.map(eventId => `event_id=${eventId}`),
  361. ].join('&');
  362. const res: IssueAttachment[] = await this.api.requestPromise(
  363. `/api/0/issues/${this.props.issueId}/attachments/?${queries}`
  364. );
  365. let hasMinidumps = false;
  366. res.forEach(attachment => {
  367. if (attachment.type === 'event.minidump') {
  368. hasMinidumps = true;
  369. }
  370. });
  371. this.setState({
  372. ...this.state,
  373. lastFetchedCursor: cursor,
  374. attachments: res,
  375. hasMinidumps,
  376. });
  377. };
  378. return (
  379. <div data-test-id="events-table">
  380. <DiscoverQuery
  381. eventView={eventView}
  382. orgSlug={organization.slug}
  383. location={location}
  384. setError={error => setError(error?.message)}
  385. referrer={referrer || 'api.performance.transaction-events'}
  386. useEvents
  387. >
  388. {({pageLinks, isLoading: isDiscoverQueryLoading, tableData}) => {
  389. tableData ??= {data: []};
  390. const parsedPageLinks = parseLinkHeader(pageLinks);
  391. const cursor = parsedPageLinks?.next?.cursor;
  392. const shouldFetchAttachments: boolean =
  393. !!this.props.issueId && !!cursor && this.state.lastFetchedCursor !== cursor; // Only fetch on issue details page
  394. let currentEvent = cursor?.split(':')[1] ?? 0;
  395. if (!parsedPageLinks?.next?.results && totalEventCount) {
  396. currentEvent = totalEventCount;
  397. }
  398. const paginationCaption =
  399. totalEventCount && currentEvent
  400. ? tct('Showing [currentEvent] of [totalEventCount] events', {
  401. currentEvent,
  402. totalEventCount,
  403. })
  404. : undefined;
  405. if (shouldFetchAttachments) {
  406. fetchAttachments(tableData, cursor);
  407. }
  408. joinCustomData(tableData);
  409. return (
  410. <Fragment>
  411. <GridEditable
  412. isLoading={isDiscoverQueryLoading || shouldFetchAttachments}
  413. data={tableData?.data ?? []}
  414. columnOrder={columnOrder}
  415. columnSortBy={eventView.getSorts()}
  416. grid={{
  417. onResizeColumn: this.handleResizeColumn,
  418. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  419. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  420. }}
  421. location={location}
  422. />
  423. <Pagination
  424. disabled={isDiscoverQueryLoading}
  425. caption={paginationCaption}
  426. pageLinks={pageLinks}
  427. />
  428. </Fragment>
  429. );
  430. }}
  431. </DiscoverQuery>
  432. </div>
  433. );
  434. }
  435. }
  436. const StyledIconQuestion = styled(QuestionTooltip)`
  437. position: relative;
  438. top: 1px;
  439. left: 4px;
  440. `;
  441. export default EventsTable;