eventsTable.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  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 {Client} from 'sentry/api';
  6. import GridEditable, {
  7. COL_WIDTH_UNDEFINED,
  8. GridColumn,
  9. } from 'sentry/components/gridEditable';
  10. import SortLink from 'sentry/components/gridEditable/sortLink';
  11. import Link from 'sentry/components/links/link';
  12. import Pagination from 'sentry/components/pagination';
  13. import QuestionTooltip from 'sentry/components/questionTooltip';
  14. import Tooltip from 'sentry/components/tooltip';
  15. import {t, tct} from 'sentry/locale';
  16. import {IssueAttachment, Organization, Project} from 'sentry/types';
  17. import {defined} from 'sentry/utils';
  18. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  19. import DiscoverQuery, {
  20. TableData,
  21. TableDataRow,
  22. } from 'sentry/utils/discover/discoverQuery';
  23. import EventView, {EventData, isFieldSortable} from 'sentry/utils/discover/eventView';
  24. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  25. import {
  26. fieldAlignment,
  27. getAggregateAlias,
  28. isSpanOperationBreakdownField,
  29. SPAN_OP_RELATIVE_BREAKDOWN_FIELD,
  30. } from 'sentry/utils/discover/fields';
  31. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  32. import CellAction, {Actions, updateQuery} from 'sentry/views/eventsV2/table/cellAction';
  33. import {TableColumn} from 'sentry/views/eventsV2/table/types';
  34. import {COLUMN_TITLES} from '../../data';
  35. import {
  36. generateReplayLink,
  37. generateTraceLink,
  38. generateTransactionLink,
  39. normalizeSearchConditions,
  40. } from '../utils';
  41. import OperationSort, {TitleProps} from './operationSort';
  42. export function getProjectID(
  43. eventData: EventData,
  44. projects: Project[]
  45. ): string | undefined {
  46. const projectSlug = (eventData?.project as string) || undefined;
  47. if (typeof projectSlug === undefined) {
  48. return undefined;
  49. }
  50. const project = projects.find(currentProject => currentProject.slug === projectSlug);
  51. if (!project) {
  52. return undefined;
  53. }
  54. return project.id;
  55. }
  56. class OperationTitle extends Component<TitleProps> {
  57. render() {
  58. const {onClick} = this.props;
  59. return (
  60. <div onClick={onClick}>
  61. <span>{t('operation duration')}</span>
  62. <StyledIconQuestion
  63. size="xs"
  64. position="top"
  65. title={t(
  66. `Span durations are summed over the course of an entire transaction. Any overlapping spans are only counted once.`
  67. )}
  68. />
  69. </div>
  70. );
  71. }
  72. }
  73. type Props = {
  74. eventView: EventView;
  75. location: Location;
  76. organization: Organization;
  77. routes: RouteContextInterface['routes'];
  78. setError: (msg: string | undefined) => void;
  79. transactionName: string;
  80. columnTitles?: string[];
  81. customColumns?: ('attachments' | 'minidump')[];
  82. excludedTags?: string[];
  83. issueId?: string;
  84. projectId?: string;
  85. referrer?: string;
  86. totalEventCount?: string;
  87. };
  88. type State = {
  89. attachments: IssueAttachment[];
  90. hasMinidumps: boolean;
  91. lastFetchedCursor: string;
  92. widths: number[];
  93. };
  94. class EventsTable extends Component<Props, State> {
  95. state: State = {
  96. widths: [],
  97. lastFetchedCursor: '',
  98. attachments: [],
  99. hasMinidumps: true,
  100. };
  101. api = new Client();
  102. replayLinkGenerator = generateReplayLink(this.props.routes);
  103. handleCellAction = (column: TableColumn<keyof TableDataRow>) => {
  104. return (action: Actions, value: React.ReactText) => {
  105. const {eventView, location, organization, excludedTags} = this.props;
  106. trackAnalyticsEvent({
  107. eventKey: 'performance_views.transactionEvents.cellaction',
  108. eventName: 'Performance Views: Transaction Events Tab Cell Action Clicked',
  109. organization_id: parseInt(organization.id, 10),
  110. action,
  111. });
  112. const searchConditions = normalizeSearchConditions(eventView.query);
  113. if (excludedTags) {
  114. excludedTags.forEach(tag => {
  115. searchConditions.removeFilter(tag);
  116. });
  117. }
  118. updateQuery(searchConditions, action, column, value);
  119. browserHistory.push({
  120. pathname: location.pathname,
  121. query: {
  122. ...location.query,
  123. cursor: undefined,
  124. query: searchConditions.formatString(),
  125. },
  126. });
  127. };
  128. };
  129. renderBodyCell(
  130. tableData: TableData | null,
  131. column: TableColumn<keyof TableDataRow>,
  132. dataRow: TableDataRow
  133. ): React.ReactNode {
  134. const {eventView, organization, location, transactionName, projectId} = this.props;
  135. if (!tableData || !tableData.meta) {
  136. return dataRow[column.key];
  137. }
  138. const tableMeta = tableData.meta;
  139. const field = String(column.key);
  140. const fieldRenderer = getFieldRenderer(field, tableMeta);
  141. const rendered = fieldRenderer(dataRow, {
  142. organization,
  143. location,
  144. eventView,
  145. projectId,
  146. });
  147. const allowActions = [
  148. Actions.ADD,
  149. Actions.EXCLUDE,
  150. Actions.SHOW_GREATER_THAN,
  151. Actions.SHOW_LESS_THAN,
  152. ];
  153. if (['attachments', 'minidump'].includes(field)) {
  154. return rendered;
  155. }
  156. if (field === 'id' || field === 'trace') {
  157. const {issueId} = this.props;
  158. const isIssue: boolean = !!issueId;
  159. let target: LocationDescriptor = {};
  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 {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 eventIdMap = {};
  350. data.forEach(event => {
  351. event.attachments = [] as any;
  352. eventIdMap[event.id] = event;
  353. });
  354. this.state.attachments.forEach(attachment => {
  355. const eventAttachments = eventIdMap[attachment.event_id]?.attachments;
  356. if (eventAttachments) {
  357. eventAttachments.push(attachment);
  358. }
  359. });
  360. };
  361. const fetchAttachments = async ({data}: TableData, cursor: string) => {
  362. const eventIds = data.map(value => value.id);
  363. const fetchOnlyMinidumps = !this.props.customColumns?.includes('attachments');
  364. const queries: string = [
  365. 'per_page=50',
  366. ...(fetchOnlyMinidumps ? ['types=event.minidump'] : []),
  367. ...eventIds.map(eventId => `event_id=${eventId}`),
  368. ].join('&');
  369. const res: IssueAttachment[] = await this.api.requestPromise(
  370. `/api/0/issues/${this.props.issueId}/attachments/?${queries}`
  371. );
  372. let hasMinidumps = false;
  373. res.forEach(attachment => {
  374. if (attachment.type === 'event.minidump') {
  375. hasMinidumps = true;
  376. }
  377. });
  378. this.setState({
  379. ...this.state,
  380. lastFetchedCursor: cursor,
  381. attachments: res,
  382. hasMinidumps,
  383. });
  384. };
  385. return (
  386. <div>
  387. <DiscoverQuery
  388. eventView={eventView}
  389. orgSlug={organization.slug}
  390. location={location}
  391. setError={error => setError(error?.message)}
  392. referrer={referrer || 'api.performance.transaction-events'}
  393. useEvents
  394. >
  395. {({pageLinks, isLoading: isDiscoverQueryLoading, tableData}) => {
  396. tableData ??= {data: []};
  397. const parsedPageLinks = parseLinkHeader(pageLinks);
  398. const cursor = parsedPageLinks?.next?.cursor;
  399. const shouldFetchAttachments = !!this.props.issueId; // Only fetch on issue details page
  400. let currentEvent = cursor?.split(':')[1] ?? 0;
  401. if (!parsedPageLinks?.next?.results && totalEventCount) {
  402. currentEvent = totalEventCount;
  403. }
  404. const paginationCaption =
  405. totalEventCount && currentEvent
  406. ? tct('Showing [currentEvent] of [totalEventCount] events', {
  407. currentEvent,
  408. totalEventCount,
  409. })
  410. : undefined;
  411. if (
  412. shouldFetchAttachments &&
  413. cursor &&
  414. this.state.lastFetchedCursor !== cursor
  415. ) {
  416. fetchAttachments(tableData, cursor);
  417. }
  418. joinCustomData(tableData);
  419. return (
  420. <Fragment>
  421. <GridEditable
  422. isLoading={isDiscoverQueryLoading}
  423. data={tableData?.data ?? []}
  424. columnOrder={columnOrder}
  425. columnSortBy={eventView.getSorts()}
  426. grid={{
  427. onResizeColumn: this.handleResizeColumn,
  428. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  429. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  430. }}
  431. location={location}
  432. />
  433. <Pagination
  434. disabled={isDiscoverQueryLoading}
  435. caption={paginationCaption}
  436. pageLinks={pageLinks}
  437. />
  438. </Fragment>
  439. );
  440. }}
  441. </DiscoverQuery>
  442. </div>
  443. );
  444. }
  445. }
  446. const StyledIconQuestion = styled(QuestionTooltip)`
  447. position: relative;
  448. top: 1px;
  449. left: 4px;
  450. `;
  451. export default EventsTable;