asyncComponent.tsx 13 KB

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