index.tsx 7.3 KB

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