asyncComponent.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448
  1. import * as React from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import * as Sentry from '@sentry/react';
  4. import isEqual from 'lodash/isEqual';
  5. import PropTypes from 'prop-types';
  6. import {Client, ResponseMeta} from 'sentry/api';
  7. import AsyncComponentSearchInput from 'sentry/components/asyncComponentSearchInput';
  8. import LoadingError from 'sentry/components/loadingError';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import {t} from 'sentry/locale';
  11. import {metric} from 'sentry/utils/analytics';
  12. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  13. import PermissionDenied from 'sentry/views/permissionDenied';
  14. import RouteError from 'sentry/views/routeError';
  15. type AsyncComponentProps = Partial<RouteComponentProps<{}, {}>>;
  16. type AsyncComponentState = {
  17. loading: boolean;
  18. reloading: boolean;
  19. error: boolean;
  20. errors: Record<string, ResponseMeta>;
  21. remainingRequests?: number;
  22. [key: string]: any;
  23. };
  24. type SearchInputProps = React.ComponentProps<typeof AsyncComponentSearchInput>;
  25. type RenderSearchInputArgs = Omit<
  26. SearchInputProps,
  27. 'api' | 'onSuccess' | 'onError' | 'url' | keyof RouteComponentProps<{}, {}>
  28. > & {
  29. stateKey?: string;
  30. url?: SearchInputProps['url'];
  31. };
  32. /**
  33. * Wraps methods on the AsyncComponent to catch errors and set the `error`
  34. * state on error.
  35. */
  36. function wrapErrorHandling<T extends any[], U>(
  37. component: AsyncComponent,
  38. fn: (...args: T) => U
  39. ) {
  40. return (...args: T): U | null => {
  41. try {
  42. return fn(...args);
  43. } catch (error) {
  44. // eslint-disable-next-line no-console
  45. console.error(error);
  46. setTimeout(() => {
  47. throw error;
  48. });
  49. component.setState({error});
  50. return null;
  51. }
  52. };
  53. }
  54. class AsyncComponent<
  55. P extends AsyncComponentProps = AsyncComponentProps,
  56. S extends AsyncComponentState = AsyncComponentState
  57. > extends React.Component<P, S> {
  58. static contextTypes = {
  59. router: PropTypes.object,
  60. };
  61. /**
  62. * Override this flag to have the component reload its state when the window
  63. * becomes visible again. This will set the loading and reloading state, but
  64. * will not render a loading state during reloading.
  65. *
  66. * eslint-disable-next-line react/sort-comp
  67. */
  68. reloadOnVisible = false;
  69. /**
  70. * When enabling reloadOnVisible, this flag may be used to turn on and off
  71. * the reloading. This is useful if your component only needs to reload when
  72. * becoming visible during certain states.
  73. *
  74. * eslint-disable-next-line react/sort-comp
  75. */
  76. shouldReloadOnVisible = false;
  77. /**
  78. * This affects how the component behaves when `remountComponent` is called
  79. * By default, the component gets put back into a "loading" state when re-fetching data.
  80. * If this is true, then when we fetch data, the original ready component remains mounted
  81. * and it will need to handle any additional "reloading" states
  82. */
  83. shouldReload = false;
  84. /**
  85. * should `renderError` render the `detail` attribute of a 400 error
  86. */
  87. shouldRenderBadRequests = false;
  88. constructor(props: P, context: any) {
  89. super(props, context);
  90. this.fetchData = wrapErrorHandling(this, this.fetchData.bind(this));
  91. this.render = wrapErrorHandling(this, this.render.bind(this));
  92. this.state = this.getDefaultState() as Readonly<S>;
  93. this._measurement = {
  94. hasMeasured: false,
  95. };
  96. if (props.routes && props.routes) {
  97. metric.mark({name: `async-component-${getRouteStringFromRoutes(props.routes)}`});
  98. }
  99. }
  100. UNSAFE_componentWillMount() {
  101. this.api = new Client();
  102. this.fetchData();
  103. if (this.reloadOnVisible) {
  104. document.addEventListener('visibilitychange', this.visibilityReloader);
  105. }
  106. }
  107. componentDidUpdate(prevProps: P, prevContext: any) {
  108. const isRouterInContext = !!prevContext.router;
  109. const isLocationInProps = prevProps.location !== undefined;
  110. const currentLocation = isLocationInProps
  111. ? this.props.location
  112. : isRouterInContext
  113. ? this.context.router.location
  114. : null;
  115. const prevLocation = isLocationInProps
  116. ? prevProps.location
  117. : isRouterInContext
  118. ? prevContext.router.location
  119. : null;
  120. if (!(currentLocation && prevLocation)) {
  121. return;
  122. }
  123. // Take a measurement from when this component is initially created until it finishes it's first
  124. // set of API requests
  125. if (
  126. !this._measurement.hasMeasured &&
  127. this._measurement.finished &&
  128. this.props.routes
  129. ) {
  130. const routeString = getRouteStringFromRoutes(this.props.routes);
  131. metric.measure({
  132. name: 'app.component.async-component',
  133. start: `async-component-${routeString}`,
  134. data: {
  135. route: routeString,
  136. error: this._measurement.error,
  137. },
  138. });
  139. this._measurement.hasMeasured = true;
  140. }
  141. // Re-fetch data when router params change.
  142. if (
  143. !isEqual(this.props.params, prevProps.params) ||
  144. currentLocation.search !== prevLocation.search ||
  145. currentLocation.state !== prevLocation.state
  146. ) {
  147. this.remountComponent();
  148. }
  149. }
  150. componentWillUnmount() {
  151. this.api.clear();
  152. document.removeEventListener('visibilitychange', this.visibilityReloader);
  153. }
  154. api: Client = new Client();
  155. private _measurement: any;
  156. // XXX: can't call this getInitialState as React whines
  157. getDefaultState(): AsyncComponentState {
  158. const endpoints = this.getEndpoints();
  159. const state = {
  160. // has all data finished requesting?
  161. loading: true,
  162. // is the component reload
  163. reloading: false,
  164. // is there an error loading ANY data?
  165. error: false,
  166. errors: {},
  167. };
  168. endpoints.forEach(([stateKey, _endpoint]) => {
  169. state[stateKey] = null;
  170. });
  171. return state;
  172. }
  173. // Check if we should measure render time for this component
  174. markShouldMeasure = ({
  175. remainingRequests,
  176. error,
  177. }: {remainingRequests?: number; error?: any} = {}) => {
  178. if (!this._measurement.hasMeasured) {
  179. this._measurement.finished = remainingRequests === 0;
  180. this._measurement.error = error || this._measurement.error;
  181. }
  182. };
  183. remountComponent = () => {
  184. if (this.shouldReload) {
  185. this.reloadData();
  186. } else {
  187. this.setState(this.getDefaultState(), this.fetchData);
  188. }
  189. };
  190. visibilityReloader = () =>
  191. this.shouldReloadOnVisible &&
  192. !this.state.loading &&
  193. !document.hidden &&
  194. this.reloadData();
  195. reloadData() {
  196. this.fetchData({reloading: true});
  197. }
  198. fetchData = (extraState?: object) => {
  199. const endpoints = this.getEndpoints();
  200. if (!endpoints.length) {
  201. this.setState({loading: false, error: false});
  202. return;
  203. }
  204. // Cancel any in flight requests
  205. this.api.clear();
  206. this.setState({
  207. loading: true,
  208. error: false,
  209. remainingRequests: endpoints.length,
  210. ...extraState,
  211. });
  212. endpoints.forEach(([stateKey, endpoint, params, options]) => {
  213. options = options || {};
  214. // If you're using nested async components/views make sure to pass the
  215. // props through so that the child component has access to props.location
  216. const locationQuery = (this.props.location && this.props.location.query) || {};
  217. let query = (params && params.query) || {};
  218. // If paginate option then pass entire `query` object to API call
  219. // It should only be expecting `query.cursor` for pagination
  220. if ((options.paginate || locationQuery.cursor) && !options.disableEntireQuery) {
  221. query = {...locationQuery, ...query};
  222. }
  223. this.api.request(endpoint, {
  224. method: 'GET',
  225. ...params,
  226. query,
  227. success: (data, _, resp) => {
  228. this.handleRequestSuccess({stateKey, data, resp}, true);
  229. },
  230. error: error => {
  231. // Allow endpoints to fail
  232. // allowError can have side effects to handle the error
  233. if (options.allowError && options.allowError(error)) {
  234. error = null;
  235. }
  236. this.handleError(error, [stateKey, endpoint, params, options]);
  237. },
  238. });
  239. });
  240. };
  241. onRequestSuccess(_resp /* {stateKey, data, resp} */) {
  242. // Allow children to implement this
  243. }
  244. onRequestError(_resp, _args) {
  245. // Allow children to implement this
  246. }
  247. onLoadAllEndpointsSuccess() {
  248. // Allow children to implement this
  249. }
  250. handleRequestSuccess({stateKey, data, resp}, initialRequest?: boolean) {
  251. this.setState(
  252. prevState => {
  253. const state = {
  254. [stateKey]: data,
  255. // TODO(billy): This currently fails if this request is retried by SudoModal
  256. [`${stateKey}PageLinks`]: resp?.getResponseHeader('Link'),
  257. };
  258. if (initialRequest) {
  259. state.remainingRequests = prevState.remainingRequests! - 1;
  260. state.loading = prevState.remainingRequests! > 1;
  261. state.reloading = prevState.reloading && state.loading;
  262. this.markShouldMeasure({remainingRequests: state.remainingRequests});
  263. }
  264. return state;
  265. },
  266. () => {
  267. // if everything is loaded and we don't have an error, call the callback
  268. if (this.state.remainingRequests === 0 && !this.state.error) {
  269. this.onLoadAllEndpointsSuccess();
  270. }
  271. }
  272. );
  273. this.onRequestSuccess({stateKey, data, resp});
  274. }
  275. handleError(error, args) {
  276. const [stateKey] = args;
  277. if (error && error.responseText) {
  278. Sentry.addBreadcrumb({
  279. message: error.responseText,
  280. category: 'xhr',
  281. level: Sentry.Severity.Error,
  282. });
  283. }
  284. this.setState(prevState => {
  285. const loading = prevState.remainingRequests! > 1;
  286. const state: AsyncComponentState = {
  287. [stateKey]: null,
  288. errors: {
  289. ...prevState.errors,
  290. [stateKey]: error,
  291. },
  292. error: prevState.error || !!error,
  293. remainingRequests: prevState.remainingRequests! - 1,
  294. loading,
  295. reloading: prevState.reloading && loading,
  296. };
  297. this.markShouldMeasure({remainingRequests: state.remainingRequests, error: true});
  298. return state;
  299. });
  300. this.onRequestError(error, args);
  301. }
  302. /**
  303. * Return a list of endpoint queries to make.
  304. *
  305. * return [
  306. * ['stateKeyName', '/endpoint/', {optional: 'query params'}, {options}]
  307. * ]
  308. */
  309. getEndpoints(): Array<[string, string, any?, any?]> {
  310. return [];
  311. }
  312. renderSearchInput({stateKey, url, ...props}: RenderSearchInputArgs) {
  313. const [firstEndpoint] = this.getEndpoints() || [null];
  314. const stateKeyOrDefault = stateKey || (firstEndpoint && firstEndpoint[0]);
  315. const urlOrDefault = url || (firstEndpoint && firstEndpoint[1]);
  316. return (
  317. <AsyncComponentSearchInput
  318. url={urlOrDefault}
  319. {...props}
  320. api={this.api}
  321. onSuccess={(data, resp) => {
  322. this.handleRequestSuccess({stateKey: stateKeyOrDefault, data, resp});
  323. }}
  324. onError={() => {
  325. this.renderError(new Error('Error with AsyncComponentSearchInput'));
  326. }}
  327. />
  328. );
  329. }
  330. renderLoading(): React.ReactNode {
  331. return <LoadingIndicator />;
  332. }
  333. renderError(error?: Error, disableLog = false, disableReport = false): React.ReactNode {
  334. const {errors} = this.state;
  335. // 401s are captured by SudoModal, but may be passed back to AsyncComponent if they close the modal without identifying
  336. const unauthorizedErrors = Object.values(errors).find(resp => resp?.status === 401);
  337. // Look through endpoint results to see if we had any 403s, means their role can not access resource
  338. const permissionErrors = Object.values(errors).find(resp => resp?.status === 403);
  339. // If all error responses have status code === 0, then show error message but don't
  340. // log it to sentry
  341. const shouldLogSentry =
  342. !!Object.values(errors).find(resp => resp?.status !== 0) || disableLog;
  343. if (unauthorizedErrors) {
  344. return (
  345. <LoadingError message={t('You are not authorized to access this resource.')} />
  346. );
  347. }
  348. if (permissionErrors) {
  349. return <PermissionDenied />;
  350. }
  351. if (this.shouldRenderBadRequests) {
  352. const badRequests = Object.values(errors)
  353. .filter(resp => resp?.status === 400 && resp?.responseJSON?.detail)
  354. .map(resp => resp.responseJSON.detail);
  355. if (badRequests.length) {
  356. return <LoadingError message={[...new Set(badRequests)].join('\n')} />;
  357. }
  358. }
  359. return (
  360. <RouteError
  361. error={error}
  362. disableLogSentry={!shouldLogSentry}
  363. disableReport={disableReport}
  364. />
  365. );
  366. }
  367. get shouldRenderLoading() {
  368. return this.state.loading && (!this.shouldReload || !this.state.reloading);
  369. }
  370. renderComponent() {
  371. return this.shouldRenderLoading
  372. ? this.renderLoading()
  373. : this.state.error
  374. ? this.renderError(new Error('Unable to load all required endpoints'))
  375. : this.renderBody();
  376. }
  377. /**
  378. * Renders once all endpoints have been loaded
  379. */
  380. renderBody(): React.ReactNode {
  381. // Allow children to implement this
  382. throw new Error('Not implemented');
  383. }
  384. render() {
  385. return this.renderComponent();
  386. }
  387. }
  388. export default AsyncComponent;