asyncComponent.tsx 13 KB

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