organizationContextContainer.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. import {Component, Fragment} from 'react';
  2. import {PlainRoute, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import {openSudo} from 'sentry/actionCreators/modal';
  6. import {fetchOrganizationDetails} from 'sentry/actionCreators/organization';
  7. import {Client} from 'sentry/api';
  8. import {Alert} from 'sentry/components/alert';
  9. import LoadingError from 'sentry/components/loadingError';
  10. import LoadingTriangle from 'sentry/components/loadingTriangle';
  11. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  12. import Sidebar from 'sentry/components/sidebar';
  13. import {ORGANIZATION_FETCH_ERROR_TYPES} from 'sentry/constants';
  14. import {t} from 'sentry/locale';
  15. import SentryTypes from 'sentry/sentryTypes';
  16. import ConfigStore from 'sentry/stores/configStore';
  17. import HookStore from 'sentry/stores/hookStore';
  18. import OrganizationStore from 'sentry/stores/organizationStore';
  19. import {space} from 'sentry/styles/space';
  20. import {Organization} from 'sentry/types';
  21. import {metric} from 'sentry/utils/analytics';
  22. import {callIfFunction} from 'sentry/utils/callIfFunction';
  23. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  24. import RequestError from 'sentry/utils/requestError/requestError';
  25. import withApi from 'sentry/utils/withApi';
  26. import withOrganizations from 'sentry/utils/withOrganizations';
  27. import {OrganizationContext} from './organizationContext';
  28. type Props = RouteComponentProps<{orgId: string}, {}> & {
  29. api: Client;
  30. includeSidebar: boolean;
  31. organizations: Organization[];
  32. organizationsLoading: boolean;
  33. routes: PlainRoute[];
  34. useLastOrganization: boolean;
  35. children?: React.ReactNode;
  36. };
  37. type State = {
  38. loading: boolean;
  39. organization: Organization | null;
  40. prevProps: {
  41. location: Props['location'];
  42. orgId: string;
  43. organizationsLoading: boolean;
  44. };
  45. dirty?: boolean;
  46. error?: RequestError | null;
  47. errorType?: string | null;
  48. hooks?: React.ReactNode[];
  49. };
  50. class OrganizationContextContainer extends Component<Props, State> {
  51. static getDerivedStateFromProps(props: Readonly<Props>, prevState: State): State {
  52. const {prevProps} = prevState;
  53. if (OrganizationContextContainer.shouldRemount(prevProps, props)) {
  54. return OrganizationContextContainer.getDefaultState(props);
  55. }
  56. const {organizationsLoading, location, params} = props;
  57. const {orgId} = params;
  58. return {
  59. ...prevState,
  60. prevProps: {
  61. orgId,
  62. organizationsLoading,
  63. location,
  64. },
  65. };
  66. }
  67. static shouldRemount(prevProps: State['prevProps'], props: Props): boolean {
  68. const hasOrgIdAndChanged =
  69. prevProps.orgId && props.params.orgId && prevProps.orgId !== props.params.orgId;
  70. const hasOrgId =
  71. props.params.orgId ||
  72. (props.useLastOrganization && ConfigStore.get('lastOrganization'));
  73. // protect against the case where we finish fetching org details
  74. // and then `OrganizationsStore` finishes loading:
  75. // only fetch in the case where we don't have an orgId
  76. //
  77. // Compare `getOrganizationSlug` because we may have a last used org from server
  78. // if there is no orgId in the URL
  79. const organizationLoadingChanged =
  80. prevProps.organizationsLoading !== props.organizationsLoading &&
  81. props.organizationsLoading === false;
  82. return (
  83. hasOrgIdAndChanged ||
  84. (!hasOrgId && organizationLoadingChanged) ||
  85. (props.location.state === 'refresh' && prevProps.location.state !== 'refresh')
  86. );
  87. }
  88. static getDefaultState(props: Props): State {
  89. const prevProps = {
  90. orgId: props.params.orgId,
  91. organizationsLoading: props.organizationsLoading,
  92. location: props.location,
  93. };
  94. if (OrganizationContextContainer.isOrgStorePopulatedCorrectly(props)) {
  95. // retrieve initial state from store
  96. return {
  97. ...OrganizationStore.get(),
  98. prevProps,
  99. };
  100. }
  101. return {
  102. loading: true,
  103. error: null,
  104. errorType: null,
  105. organization: null,
  106. prevProps,
  107. };
  108. }
  109. static getOrganizationSlug(props: Props) {
  110. return (
  111. props.params.orgId ||
  112. ((props.useLastOrganization &&
  113. (ConfigStore.get('lastOrganization') ||
  114. props.organizations?.[0]?.slug)) as string)
  115. );
  116. }
  117. static isOrgChanging(props: Props): boolean {
  118. const {organization} = OrganizationStore.get();
  119. if (!organization) {
  120. return false;
  121. }
  122. return organization.slug !== OrganizationContextContainer.getOrganizationSlug(props);
  123. }
  124. static isOrgStorePopulatedCorrectly(props: Props) {
  125. const {organization, dirty} = OrganizationStore.get();
  126. return !dirty && organization && !OrganizationContextContainer.isOrgChanging(props);
  127. }
  128. static childContextTypes = {
  129. organization: SentryTypes.Organization,
  130. };
  131. constructor(props: Props) {
  132. super(props);
  133. this.state = OrganizationContextContainer.getDefaultState(props);
  134. }
  135. getChildContext() {
  136. return {
  137. organization: this.state.organization,
  138. };
  139. }
  140. componentDidMount() {
  141. this.fetchData(true);
  142. }
  143. componentDidUpdate(prevProps: Props) {
  144. const remountPrevProps: State['prevProps'] = {
  145. orgId: prevProps.params.orgId,
  146. organizationsLoading: prevProps.organizationsLoading,
  147. location: prevProps.location,
  148. };
  149. if (OrganizationContextContainer.shouldRemount(remountPrevProps, this.props)) {
  150. this.remountComponent();
  151. }
  152. }
  153. componentWillUnmount() {
  154. this.unlisteners.forEach(callIfFunction);
  155. }
  156. unlisteners = [
  157. OrganizationStore.listen(data => this.loadOrganization(data), undefined),
  158. ];
  159. remountComponent = () => {
  160. this.setState(
  161. OrganizationContextContainer.getDefaultState(this.props),
  162. this.fetchData
  163. );
  164. };
  165. isLoading() {
  166. // In the absence of an organization slug, the loading state should be
  167. // derived from this.props.organizationsLoading from OrganizationsStore
  168. if (!OrganizationContextContainer.getOrganizationSlug(this.props)) {
  169. return this.props.organizationsLoading;
  170. }
  171. return this.state.loading;
  172. }
  173. fetchData(isInitialFetch = false) {
  174. const orgSlug = OrganizationContextContainer.getOrganizationSlug(this.props);
  175. if (!orgSlug) {
  176. return;
  177. }
  178. // fetch from the store, then fetch from the API if necessary
  179. if (OrganizationContextContainer.isOrgStorePopulatedCorrectly(this.props)) {
  180. return;
  181. }
  182. metric.mark({name: 'organization-details-fetch-start'});
  183. fetchOrganizationDetails(
  184. this.props.api,
  185. orgSlug,
  186. !OrganizationContextContainer.isOrgChanging(this.props), // if true, will preserve a lightweight org that was fetched,
  187. isInitialFetch
  188. );
  189. }
  190. loadOrganization(orgData: State) {
  191. const {organization, error} = orgData;
  192. const hooks: React.ReactNode[] = [];
  193. if (organization && !error) {
  194. HookStore.get('organization:header').forEach(cb => {
  195. hooks.push(cb(organization));
  196. });
  197. // Configure scope to have organization tag
  198. Sentry.configureScope(scope => {
  199. // XXX(dcramer): this is duplicated in sdk.py on the backend
  200. scope.setTag('organization', organization.id);
  201. scope.setTag('organization.slug', organization.slug);
  202. scope.setContext('organization', {id: organization.id, slug: organization.slug});
  203. });
  204. } else if (error) {
  205. // If user is superuser, open sudo window
  206. const user = ConfigStore.get('user');
  207. if (!user || !user.isSuperuser || error.status !== 403) {
  208. // This `catch` can swallow up errors in development (and tests)
  209. // So let's log them. This may create some noise, especially the test case where
  210. // we specifically test this branch
  211. console.error(error); // eslint-disable-line no-console
  212. } else {
  213. openSudo({
  214. retryRequest: () => Promise.resolve(this.fetchData()),
  215. isSuperuser: true,
  216. needsReload: true,
  217. });
  218. }
  219. }
  220. this.setState({...orgData, hooks}, () => {
  221. // Take a measurement for when organization details are done loading and the new state is applied
  222. if (organization) {
  223. metric.measure({
  224. name: 'app.component.perf',
  225. start: 'organization-details-fetch-start',
  226. data: {
  227. name: 'org-details',
  228. route: getRouteStringFromRoutes(this.props.routes),
  229. organization_id: parseInt(organization.id, 10),
  230. },
  231. });
  232. }
  233. });
  234. }
  235. getTitle() {
  236. return this.state.organization?.name ?? 'Sentry';
  237. }
  238. renderSidebar(): React.ReactNode {
  239. if (!this.props.includeSidebar) {
  240. return null;
  241. }
  242. const {children: _, ...props} = this.props;
  243. return <Sidebar {...props} organization={this.state.organization as Organization} />;
  244. }
  245. renderError() {
  246. let errorComponent: React.ReactElement;
  247. switch (this.state.errorType) {
  248. case ORGANIZATION_FETCH_ERROR_TYPES.ORG_NO_ACCESS:
  249. // We can still render when an org can't be loaded due to 401. The
  250. // backend will handle redirects when this is a problem.
  251. return this.renderBody();
  252. case ORGANIZATION_FETCH_ERROR_TYPES.ORG_NOT_FOUND:
  253. errorComponent = (
  254. <Alert type="error" data-test-id="org-loading-error">
  255. {t('The organization you were looking for was not found.')}
  256. </Alert>
  257. );
  258. break;
  259. default:
  260. errorComponent = <LoadingError onRetry={this.remountComponent} />;
  261. }
  262. return <ErrorWrapper>{errorComponent}</ErrorWrapper>;
  263. }
  264. renderBody() {
  265. return (
  266. <SentryDocumentTitle noSuffix title={this.getTitle()}>
  267. <OrganizationContext.Provider value={this.state.organization}>
  268. <div className="app">
  269. {this.state.hooks}
  270. {this.renderSidebar()}
  271. {this.props.children}
  272. </div>
  273. </OrganizationContext.Provider>
  274. </SentryDocumentTitle>
  275. );
  276. }
  277. render() {
  278. if (this.isLoading()) {
  279. return (
  280. <LoadingTriangle>{t('Loading data for your organization.')}</LoadingTriangle>
  281. );
  282. }
  283. if (this.state.error) {
  284. return (
  285. <Fragment>
  286. {this.renderSidebar()}
  287. {this.renderError()}
  288. </Fragment>
  289. );
  290. }
  291. return this.renderBody();
  292. }
  293. }
  294. export default withApi(
  295. withOrganizations(Sentry.withProfiler(OrganizationContextContainer))
  296. );
  297. export {OrganizationContextContainer as OrganizationLegacyContext};
  298. const ErrorWrapper = styled('div')`
  299. padding: ${space(3)};
  300. `;