asyncComponent.tsx 14 KB

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