asyncComponent.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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 type AsyncComponentProps = Partial<RouteComponentProps<{}, {}>>;
  16. type 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.fetchData = wrapErrorHandling(this, this.fetchData.bind(this));
  64. this.render = wrapErrorHandling(this, this.render.bind(this));
  65. this.state = this.getDefaultState() as Readonly<S>;
  66. this._measurement = {
  67. hasMeasured: false,
  68. };
  69. if (props.routes && props.routes) {
  70. metric.mark({name: `async-component-${getRouteStringFromRoutes(props.routes)}`});
  71. }
  72. }
  73. UNSAFE_componentWillMount() {
  74. this.api = new Client();
  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. };
  175. endpoints.forEach(([stateKey, _endpoint]) => {
  176. state[stateKey] = null;
  177. });
  178. return state;
  179. }
  180. // Check if we should measure render time for this component
  181. markShouldMeasure = ({
  182. remainingRequests,
  183. error,
  184. }: {error?: any; remainingRequests?: number} = {}) => {
  185. if (!this._measurement.hasMeasured) {
  186. this._measurement.finished = remainingRequests === 0;
  187. this._measurement.error = error || this._measurement.error;
  188. }
  189. };
  190. remountComponent = () => {
  191. if (this.shouldReload) {
  192. this.reloadData();
  193. } else {
  194. this.setState(this.getDefaultState(), this.fetchData);
  195. }
  196. };
  197. visibilityReloader = () =>
  198. this.shouldReloadOnVisible &&
  199. !this.state.loading &&
  200. !document.hidden &&
  201. this.reloadData();
  202. reloadData() {
  203. this.fetchData({reloading: true});
  204. }
  205. fetchData = (extraState?: object) => {
  206. const endpoints = this.getEndpoints();
  207. if (!endpoints.length) {
  208. this.setState({loading: false, error: false});
  209. return;
  210. }
  211. // Cancel any in flight requests
  212. this.api.clear();
  213. this.setState({
  214. loading: true,
  215. error: false,
  216. remainingRequests: endpoints.length,
  217. ...extraState,
  218. });
  219. endpoints.forEach(([stateKey, endpoint, params, options]) => {
  220. options = options || {};
  221. // If you're using nested async components/views make sure to pass the
  222. // props through so that the child component has access to props.location
  223. const locationQuery = (this.props.location && this.props.location.query) || {};
  224. let query = (params && params.query) || {};
  225. // If paginate option then pass entire `query` object to API call
  226. // It should only be expecting `query.cursor` for pagination
  227. if ((options.paginate || locationQuery.cursor) && !options.disableEntireQuery) {
  228. query = {...locationQuery, ...query};
  229. }
  230. this.api.request(endpoint, {
  231. method: 'GET',
  232. ...params,
  233. query,
  234. success: (data, _, resp) => {
  235. this.handleRequestSuccess({stateKey, data, resp}, true);
  236. },
  237. error: error => {
  238. // Allow endpoints to fail
  239. // allowError can have side effects to handle the error
  240. if (options.allowError && options.allowError(error)) {
  241. error = null;
  242. }
  243. this.handleError(error, [stateKey, endpoint, params, options]);
  244. },
  245. });
  246. });
  247. };
  248. onRequestSuccess(_resp /* {stateKey, data, resp} */) {
  249. // Allow children to implement this
  250. }
  251. onRequestError(_resp, _args) {
  252. // Allow children to implement this
  253. }
  254. onLoadAllEndpointsSuccess() {
  255. // Allow children to implement this
  256. }
  257. handleRequestSuccess({stateKey, data, resp}, initialRequest?: boolean) {
  258. this.setState(
  259. prevState => {
  260. const state = {
  261. [stateKey]: data,
  262. // TODO(billy): This currently fails if this request is retried by SudoModal
  263. [`${stateKey}PageLinks`]: resp?.getResponseHeader('Link'),
  264. };
  265. if (initialRequest) {
  266. state.remainingRequests = prevState.remainingRequests! - 1;
  267. state.loading = prevState.remainingRequests! > 1;
  268. state.reloading = prevState.reloading && state.loading;
  269. this.markShouldMeasure({remainingRequests: state.remainingRequests});
  270. }
  271. return state;
  272. },
  273. () => {
  274. // if everything is loaded and we don't have an error, call the callback
  275. if (this.state.remainingRequests === 0 && !this.state.error) {
  276. this.onLoadAllEndpointsSuccess();
  277. }
  278. }
  279. );
  280. this.onRequestSuccess({stateKey, data, resp});
  281. }
  282. handleError(error, args) {
  283. const [stateKey] = args;
  284. if (error && error.responseText) {
  285. Sentry.addBreadcrumb({
  286. message: error.responseText,
  287. category: 'xhr',
  288. level: 'error',
  289. });
  290. }
  291. this.setState(prevState => {
  292. const loading = prevState.remainingRequests! > 1;
  293. const state: AsyncComponentState = {
  294. [stateKey]: null,
  295. errors: {
  296. ...prevState.errors,
  297. [stateKey]: error,
  298. },
  299. error: prevState.error || !!error,
  300. remainingRequests: prevState.remainingRequests! - 1,
  301. loading,
  302. reloading: prevState.reloading && loading,
  303. };
  304. this.markShouldMeasure({remainingRequests: state.remainingRequests, error: true});
  305. return state;
  306. });
  307. this.onRequestError(error, args);
  308. }
  309. /**
  310. * Return a list of endpoint queries to make.
  311. *
  312. * return [
  313. * ['stateKeyName', '/endpoint/', {optional: 'query params'}, {options}]
  314. * ]
  315. */
  316. getEndpoints(): Array<[string, string, any?, any?]> {
  317. return [];
  318. }
  319. renderSearchInput({stateKey, url, ...props}: RenderSearchInputArgs) {
  320. const [firstEndpoint] = this.getEndpoints() || [null];
  321. const stateKeyOrDefault = stateKey || (firstEndpoint && firstEndpoint[0]);
  322. const urlOrDefault = url || (firstEndpoint && firstEndpoint[1]);
  323. return (
  324. <AsyncComponentSearchInput
  325. url={urlOrDefault}
  326. {...props}
  327. api={this.api}
  328. onSuccess={(data, resp) => {
  329. this.handleRequestSuccess({stateKey: stateKeyOrDefault, data, resp});
  330. }}
  331. onError={() => {
  332. this.renderError(new Error('Error with AsyncComponentSearchInput'));
  333. }}
  334. />
  335. );
  336. }
  337. renderLoading(): React.ReactNode {
  338. return <LoadingIndicator />;
  339. }
  340. renderError(error?: Error, disableLog = false): React.ReactNode {
  341. const {errors} = this.state;
  342. // 401s are captured by SudoModal, but may be passed back to AsyncComponent if they close the modal without identifying
  343. const unauthorizedErrors = Object.values(errors).find(resp => resp?.status === 401);
  344. // Look through endpoint results to see if we had any 403s, means their role can not access resource
  345. const permissionErrors = Object.values(errors).find(resp => resp?.status === 403);
  346. // If all error responses have status code === 0, then show error message but don't
  347. // log it to sentry
  348. const shouldLogSentry =
  349. !!Object.values(errors).find(resp => resp?.status !== 0) || disableLog;
  350. if (unauthorizedErrors) {
  351. return (
  352. <LoadingError message={t('You are not authorized to access this resource.')} />
  353. );
  354. }
  355. if (permissionErrors) {
  356. return <PermissionDenied />;
  357. }
  358. if (this.shouldRenderBadRequests) {
  359. const badRequests = Object.values(errors)
  360. .filter(resp => resp?.status === 400 && resp?.responseJSON?.detail)
  361. .map(resp => resp.responseJSON.detail);
  362. if (badRequests.length) {
  363. return <LoadingError message={[...new Set(badRequests)].join('\n')} />;
  364. }
  365. }
  366. return (
  367. <RouteError
  368. error={error}
  369. disableLogSentry={!shouldLogSentry}
  370. disableReport={this.disableErrorReport}
  371. />
  372. );
  373. }
  374. get shouldRenderLoading() {
  375. return this.state.loading && (!this.shouldReload || !this.state.reloading);
  376. }
  377. renderComponent() {
  378. return this.shouldRenderLoading
  379. ? this.renderLoading()
  380. : this.state.error
  381. ? this.renderError(new Error('Unable to load all required endpoints'))
  382. : this.renderBody();
  383. }
  384. /**
  385. * Renders once all endpoints have been loaded
  386. */
  387. renderBody(): React.ReactNode {
  388. // Allow children to implement this
  389. throw new Error('Not implemented');
  390. }
  391. render() {
  392. return this.renderComponent();
  393. }
  394. }
  395. export default AsyncComponent;