asyncComponent.tsx 13 KB

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