index.tsx 7.6 KB

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