index.tsx 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. import {PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Location} from 'history';
  4. import {EventQuery} from 'sentry/actionCreators/events';
  5. import {Client} from 'sentry/api';
  6. import Pagination from 'sentry/components/pagination';
  7. import {t} from 'sentry/locale';
  8. import {Organization} from 'sentry/types';
  9. import {metric, trackAnalyticsEvent} from 'sentry/utils/analytics';
  10. import {CustomMeasurementsContext} from 'sentry/utils/customMeasurements/customMeasurementsContext';
  11. import {TableData} from 'sentry/utils/discover/discoverQuery';
  12. import EventView, {
  13. isAPIPayloadSimilar,
  14. LocationQuery,
  15. } from 'sentry/utils/discover/eventView';
  16. import {SPAN_OP_BREAKDOWN_FIELDS} from 'sentry/utils/discover/fields';
  17. import Measurements from 'sentry/utils/measurements/measurements';
  18. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  19. import withApi from 'sentry/utils/withApi';
  20. import TableView from './tableView';
  21. type TableProps = {
  22. api: Client;
  23. confirmedQuery: boolean;
  24. eventView: EventView;
  25. location: Location;
  26. onChangeShowTags: () => void;
  27. organization: Organization;
  28. setError: (msg: string, code: number) => void;
  29. showTags: boolean;
  30. title: string;
  31. };
  32. type TableState = {
  33. error: null | string;
  34. isLoading: boolean;
  35. pageLinks: null | string;
  36. tableData: TableData | null | undefined;
  37. tableFetchID: symbol | undefined;
  38. };
  39. /**
  40. * `Table` is a container element that handles 2 things
  41. * 1. Fetch data from source
  42. * 2. Handle pagination of data
  43. *
  44. * It will pass the data it fetched to `TableView`, where the state of the
  45. * Table is maintained and controlled
  46. */
  47. class Table extends PureComponent<TableProps, TableState> {
  48. state: TableState = {
  49. isLoading: true,
  50. tableFetchID: undefined,
  51. error: null,
  52. pageLinks: null,
  53. tableData: null,
  54. };
  55. componentDidMount() {
  56. this.fetchData();
  57. }
  58. componentDidUpdate(prevProps: TableProps) {
  59. // Reload data if we aren't already loading, or if we've moved
  60. // from an invalid view state to a valid one.
  61. if (
  62. (!this.state.isLoading && this.shouldRefetchData(prevProps)) ||
  63. (prevProps.eventView.isValid() === false && this.props.eventView.isValid()) ||
  64. prevProps.confirmedQuery !== this.props.confirmedQuery
  65. ) {
  66. this.fetchData();
  67. }
  68. }
  69. shouldRefetchData = (prevProps: TableProps): boolean => {
  70. const thisAPIPayload = this.props.eventView.getEventsAPIPayload(this.props.location);
  71. const otherAPIPayload = prevProps.eventView.getEventsAPIPayload(prevProps.location);
  72. return !isAPIPayloadSimilar(thisAPIPayload, otherAPIPayload);
  73. };
  74. fetchData = () => {
  75. const {eventView, organization, location, setError, confirmedQuery} = this.props;
  76. if (!eventView.isValid() || !confirmedQuery) {
  77. return;
  78. }
  79. // note: If the eventView has no aggregates, the endpoint will automatically add the event id in
  80. // the API payload response
  81. const shouldUseEvents = organization.features.includes(
  82. 'discover-frontend-use-events-endpoint'
  83. );
  84. const url = shouldUseEvents
  85. ? `/organizations/${organization.slug}/events/`
  86. : `/organizations/${organization.slug}/eventsv2/`;
  87. const tableFetchID = Symbol('tableFetchID');
  88. const apiPayload = eventView.getEventsAPIPayload(location) as LocationQuery &
  89. EventQuery;
  90. apiPayload.referrer = 'api.discover.query-table';
  91. setError('', 200);
  92. this.setState({isLoading: true, tableFetchID});
  93. metric.mark({name: `discover-events-start-${apiPayload.query}`});
  94. this.props.api.clear();
  95. this.props.api
  96. .requestPromise(url, {
  97. method: 'GET',
  98. includeAllArgs: true,
  99. query: apiPayload,
  100. })
  101. .then(([data, _, resp]) => {
  102. // We want to measure this metric regardless of whether we use the result
  103. metric.measure({
  104. name: 'app.api.discover-query',
  105. start: `discover-events-start-${apiPayload.query}`,
  106. data: {
  107. status: resp && resp.status,
  108. },
  109. });
  110. if (this.state.tableFetchID !== tableFetchID) {
  111. // invariant: a different request was initiated after this request
  112. return;
  113. }
  114. const {fields, ...nonFieldsMeta} = data.meta ?? {};
  115. // events api uses a different response format so we need to construct tableData differently
  116. const tableData = shouldUseEvents
  117. ? {
  118. ...data,
  119. meta: {...fields, nonFieldsMeta},
  120. }
  121. : data;
  122. this.setState(prevState => ({
  123. isLoading: false,
  124. tableFetchID: undefined,
  125. error: null,
  126. pageLinks: resp ? resp.getResponseHeader('Link') : prevState.pageLinks,
  127. tableData,
  128. }));
  129. })
  130. .catch(err => {
  131. metric.measure({
  132. name: 'app.api.discover-query',
  133. start: `discover-events-start-${apiPayload.query}`,
  134. data: {
  135. status: err.status,
  136. },
  137. });
  138. const message = err?.responseJSON?.detail || t('An unknown error occurred.');
  139. this.setState({
  140. isLoading: false,
  141. tableFetchID: undefined,
  142. error: message,
  143. pageLinks: null,
  144. tableData: null,
  145. });
  146. trackAnalyticsEvent({
  147. eventKey: 'discover_search.failed',
  148. eventName: 'Discover Search: Failed',
  149. organization_id: this.props.organization.id,
  150. search_type: 'events',
  151. search_source: 'discover_search',
  152. error: message,
  153. });
  154. setError(message, err.status);
  155. });
  156. };
  157. render() {
  158. const {eventView} = this.props;
  159. const {pageLinks, tableData, isLoading, error} = this.state;
  160. const isFirstPage = pageLinks
  161. ? parseLinkHeader(pageLinks).previous.results === false
  162. : false;
  163. return (
  164. <Container>
  165. <Measurements>
  166. {({measurements}) => {
  167. const measurementKeys = Object.values(measurements).map(({key}) => key);
  168. return (
  169. <CustomMeasurementsContext.Consumer>
  170. {contextValue => (
  171. <TableView
  172. {...this.props}
  173. isLoading={isLoading}
  174. isFirstPage={isFirstPage}
  175. error={error}
  176. eventView={eventView}
  177. tableData={tableData}
  178. measurementKeys={measurementKeys}
  179. spanOperationBreakdownKeys={SPAN_OP_BREAKDOWN_FIELDS}
  180. customMeasurements={contextValue?.customMeasurements ?? undefined}
  181. />
  182. )}
  183. </CustomMeasurementsContext.Consumer>
  184. );
  185. }}
  186. </Measurements>
  187. <Pagination pageLinks={pageLinks} />
  188. </Container>
  189. );
  190. }
  191. }
  192. export default withApi(Table);
  193. const Container = styled('div')`
  194. min-width: 0;
  195. `;