index.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import {PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import type {EventQuery} from 'sentry/actionCreators/events';
  5. import type {Client} from 'sentry/api';
  6. import type {CursorHandler} from 'sentry/components/pagination';
  7. import Pagination from 'sentry/components/pagination';
  8. import {t} from 'sentry/locale';
  9. import type {Organization} from 'sentry/types/organization';
  10. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  11. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  12. import type {TableData} from 'sentry/utils/discover/discoverQuery';
  13. import type {LocationQuery} from 'sentry/utils/discover/eventView';
  14. import type EventView from 'sentry/utils/discover/eventView';
  15. import {isAPIPayloadSimilar} from 'sentry/utils/discover/eventView';
  16. import {SPAN_OP_BREAKDOWN_FIELDS} from 'sentry/utils/discover/fields';
  17. import type {DiscoverDatasets} from 'sentry/utils/discover/types';
  18. import Measurements from 'sentry/utils/measurements/measurements';
  19. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  20. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  21. import withApi from 'sentry/utils/withApi';
  22. import TableView from './tableView';
  23. type TableProps = {
  24. api: Client;
  25. confirmedQuery: boolean;
  26. eventView: EventView;
  27. location: Location;
  28. onChangeShowTags: () => void;
  29. onCursor: CursorHandler;
  30. organization: Organization;
  31. setError: (msg: string, code: number) => void;
  32. showTags: boolean;
  33. title: string;
  34. dataset?: DiscoverDatasets;
  35. isHomepage?: boolean;
  36. setSplitDecision?: (value: string) => void;
  37. setTips?: (tips: string[]) => void;
  38. };
  39. type TableState = {
  40. error: null | string;
  41. isLoading: boolean;
  42. pageLinks: null | string;
  43. prevView: null | EventView;
  44. tableData: TableData | null | undefined;
  45. tableFetchID: symbol | undefined;
  46. };
  47. /**
  48. * `Table` is a container element that handles 2 things
  49. * 1. Fetch data from source
  50. * 2. Handle pagination of data
  51. *
  52. * It will pass the data it fetched to `TableView`, where the state of the
  53. * Table is maintained and controlled
  54. */
  55. class Table extends PureComponent<TableProps, TableState> {
  56. state: TableState = {
  57. isLoading: true,
  58. tableFetchID: undefined,
  59. error: null,
  60. pageLinks: null,
  61. tableData: null,
  62. prevView: null,
  63. };
  64. componentDidMount() {
  65. this.fetchData();
  66. }
  67. componentDidUpdate(prevProps: TableProps) {
  68. // Reload data if we aren't already loading, or if we've moved
  69. // from an invalid view state to a valid one.
  70. if (
  71. (!this.state.isLoading && this.shouldRefetchData(prevProps)) ||
  72. (prevProps.eventView.isValid() === false && this.props.eventView.isValid()) ||
  73. (prevProps.confirmedQuery !== this.props.confirmedQuery && this.didViewChange())
  74. ) {
  75. this.fetchData();
  76. }
  77. }
  78. didViewChange = (): boolean => {
  79. const {prevView} = this.state;
  80. const thisAPIPayload = this.props.eventView.getEventsAPIPayload(this.props.location);
  81. if (prevView === null) {
  82. return true;
  83. }
  84. const otherAPIPayload = prevView.getEventsAPIPayload(this.props.location);
  85. return !isAPIPayloadSimilar(thisAPIPayload, otherAPIPayload);
  86. };
  87. shouldRefetchData = (prevProps: TableProps): boolean => {
  88. const thisAPIPayload = this.props.eventView.getEventsAPIPayload(this.props.location);
  89. const otherAPIPayload = prevProps.eventView.getEventsAPIPayload(prevProps.location);
  90. return !isAPIPayloadSimilar(thisAPIPayload, otherAPIPayload);
  91. };
  92. fetchData = () => {
  93. const {
  94. eventView,
  95. organization,
  96. location,
  97. setError,
  98. confirmedQuery,
  99. setTips,
  100. setSplitDecision,
  101. } = this.props;
  102. if (!eventView.isValid() || !confirmedQuery) {
  103. return;
  104. }
  105. this.setState({prevView: eventView});
  106. // note: If the eventView has no aggregates, the endpoint will automatically add the event id in
  107. // the API payload response
  108. const url = `/organizations/${organization.slug}/events/`;
  109. const tableFetchID = Symbol('tableFetchID');
  110. const apiPayload = eventView.getEventsAPIPayload(location) as LocationQuery &
  111. EventQuery;
  112. // We are now routing to the trace view on clicking event ids. Therefore, we need the trace slug associated to the event id.
  113. // Note: Event ID or 'id' is added to the fields in the API payload response by default for all non-aggregate queries.
  114. if (!eventView.hasAggregateField() || apiPayload.field.includes('id')) {
  115. apiPayload.field.push('trace');
  116. // We need to include the event.type field because we want to
  117. // route to issue details for error and default event types.
  118. apiPayload.field.push('event.type');
  119. }
  120. // To generate the target url for TRACE ID and EVENT ID links we always include a timestamp,
  121. // to speed up the trace endpoint. Adding timestamp for the non-aggregate case and
  122. // max(timestamp) for the aggregate case as fields, to accomodate this.
  123. if (
  124. eventView.hasAggregateField() &&
  125. apiPayload.field.includes('trace') &&
  126. !apiPayload.field.includes('max(timestamp)') &&
  127. !apiPayload.field.includes('timestamp')
  128. ) {
  129. apiPayload.field.push('max(timestamp)');
  130. } else if (
  131. apiPayload.field.includes('trace') &&
  132. !apiPayload.field.includes('timestamp')
  133. ) {
  134. apiPayload.field.push('timestamp');
  135. }
  136. if (
  137. organization.features.includes('performance-discover-dataset-selector') &&
  138. eventView.id
  139. ) {
  140. apiPayload.discoverSavedQueryId = eventView.id;
  141. }
  142. apiPayload.referrer = 'api.discover.query-table';
  143. setError('', 200);
  144. this.setState({isLoading: true, tableFetchID});
  145. metric.mark({name: `discover-events-start-${apiPayload.query}`});
  146. this.props.api.clear();
  147. this.props.api
  148. .requestPromise(url, {
  149. method: 'GET',
  150. includeAllArgs: true,
  151. query: apiPayload,
  152. })
  153. .then(([data, _, resp]) => {
  154. // We want to measure this metric regardless of whether we use the result
  155. metric.measure({
  156. name: 'app.api.discover-query',
  157. start: `discover-events-start-${apiPayload.query}`,
  158. data: {
  159. status: resp?.status,
  160. },
  161. });
  162. if (this.state.tableFetchID !== tableFetchID) {
  163. // invariant: a different request was initiated after this request
  164. return;
  165. }
  166. const {fields, ...nonFieldsMeta} = data.meta ?? {};
  167. // events api uses a different response format so we need to construct tableData differently
  168. const tableData = {
  169. ...data,
  170. meta: {...fields, ...nonFieldsMeta},
  171. };
  172. trackAnalytics('discover_search.success', {
  173. has_results: tableData.data.length > 0,
  174. organization: this.props.organization,
  175. search_type: 'events',
  176. search_source: 'discover_search',
  177. });
  178. this.setState(prevState => ({
  179. isLoading: false,
  180. tableFetchID: undefined,
  181. error: null,
  182. pageLinks: resp ? resp.getResponseHeader('Link') : prevState.pageLinks,
  183. tableData,
  184. }));
  185. const tips: string[] = [];
  186. const {query, columns} = tableData?.meta?.tips ?? {};
  187. if (query) {
  188. tips.push(query);
  189. }
  190. if (columns) {
  191. tips.push(columns);
  192. }
  193. setTips?.(tips);
  194. const splitDecision = tableData?.meta?.discoverSplitDecision;
  195. if (splitDecision) {
  196. setSplitDecision?.(splitDecision);
  197. }
  198. })
  199. .catch(err => {
  200. metric.measure({
  201. name: 'app.api.discover-query',
  202. start: `discover-events-start-${apiPayload.query}`,
  203. data: {
  204. status: err.status,
  205. },
  206. });
  207. const message = err?.responseJSON?.detail || t('An unknown error occurred.');
  208. this.setState({
  209. isLoading: false,
  210. tableFetchID: undefined,
  211. error: message,
  212. pageLinks: null,
  213. tableData: null,
  214. });
  215. trackAnalytics('discover_search.failed', {
  216. organization: this.props.organization,
  217. search_type: 'events',
  218. search_source: 'discover_search',
  219. error: message,
  220. });
  221. setError(message, err.status);
  222. });
  223. };
  224. render() {
  225. const {eventView, onCursor, dataset} = this.props;
  226. const {pageLinks, tableData, isLoading, error} = this.state;
  227. const isFirstPage = pageLinks
  228. ? parseLinkHeader(pageLinks).previous.results === false
  229. : false;
  230. return (
  231. <Container>
  232. <Measurements>
  233. {({measurements}) => {
  234. const measurementKeys = Object.values(measurements).map(({key}) => key);
  235. return (
  236. <CustomMeasurementsContext.Consumer>
  237. {contextValue => (
  238. <VisuallyCompleteWithData
  239. id="Discover-Table"
  240. hasData={(tableData?.data?.length ?? 0) > 0}
  241. isLoading={isLoading}
  242. >
  243. <TableView
  244. {...this.props}
  245. isLoading={isLoading}
  246. isFirstPage={isFirstPage}
  247. error={error}
  248. eventView={eventView}
  249. tableData={tableData}
  250. measurementKeys={measurementKeys}
  251. spanOperationBreakdownKeys={SPAN_OP_BREAKDOWN_FIELDS}
  252. customMeasurements={contextValue?.customMeasurements ?? undefined}
  253. dataset={dataset}
  254. />
  255. </VisuallyCompleteWithData>
  256. )}
  257. </CustomMeasurementsContext.Consumer>
  258. );
  259. }}
  260. </Measurements>
  261. <Pagination pageLinks={pageLinks} onCursor={onCursor} />
  262. </Container>
  263. );
  264. }
  265. }
  266. export default withApi(Table);
  267. const Container = styled('div')`
  268. min-width: 0;
  269. `;