index.tsx 11 KB

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