organizationContext.tsx 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import {
  2. Component,
  3. createContext,
  4. useCallback,
  5. useContext,
  6. useEffect,
  7. useRef,
  8. } from 'react';
  9. import {fetchOrganizationDetails} from 'sentry/actionCreators/organization';
  10. import {switchOrganization} from 'sentry/actionCreators/organizations';
  11. import {openSudo} from 'sentry/actionCreators/sudoModal';
  12. import {DEPLOY_PREVIEW_CONFIG} from 'sentry/constants';
  13. import {SentryPropTypeValidators} from 'sentry/sentryPropTypeValidators';
  14. import ConfigStore from 'sentry/stores/configStore';
  15. import OrganizationsStore from 'sentry/stores/organizationsStore';
  16. import OrganizationStore from 'sentry/stores/organizationStore';
  17. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  18. import type {Organization, User} from 'sentry/types';
  19. import {metric} from 'sentry/utils/analytics';
  20. import getRouteStringFromRoutes from 'sentry/utils/getRouteStringFromRoutes';
  21. import useApi from 'sentry/utils/useApi';
  22. import {useParams} from 'sentry/utils/useParams';
  23. import {useRoutes} from 'sentry/utils/useRoutes';
  24. /**
  25. * Holds the current organization if loaded.
  26. */
  27. export const OrganizationContext = createContext<Organization | null>(null);
  28. /**
  29. * Holds a function to load the organization.
  30. */
  31. const OrganizationLoaderContext = createContext<null | (() => void)>(null);
  32. interface Props {
  33. children: React.ReactNode;
  34. }
  35. /**
  36. * There are still a number of places where we consume the legacy organization
  37. * context. So for now we still need a component that provides this.
  38. */
  39. class LegacyOrganizationContextProvider extends Component<{
  40. value: Organization | null;
  41. children?: React.ReactNode;
  42. }> {
  43. static childContextTypes = {
  44. organization: SentryPropTypeValidators.isOrganization,
  45. };
  46. getChildContext() {
  47. return {organization: this.props.value};
  48. }
  49. render() {
  50. return this.props.children;
  51. }
  52. }
  53. /**
  54. * Ensures that an organization is loaded when the hook is used. This will only
  55. * be done on first render and if an organization is not already loaded.
  56. */
  57. export function useEnsureOrganization() {
  58. const loadOrganization = useContext(OrganizationLoaderContext);
  59. // XXX(epurkhiser): The loadOrganization function is stable as long as the
  60. // organization slug is stable. A change to the organization slug will cause
  61. // the organization to be reloaded.
  62. useEffect(() => loadOrganization?.(), [loadOrganization]);
  63. }
  64. /**
  65. * Context provider responsible for loading the organization into the
  66. * OrganizationStore if it is not already present.
  67. *
  68. * This provider *does not* immediately attempt to load the organization. A
  69. * child component must be responsible for calling `useEnsureOrganization` to
  70. * have the organization loaded.
  71. */
  72. export function OrganizationContextProvider({children}: Props) {
  73. const api = useApi();
  74. const configStore = useLegacyStore(ConfigStore);
  75. const {organizations} = useLegacyStore(OrganizationsStore);
  76. const {organization, error} = useLegacyStore(OrganizationStore);
  77. const lastOrganizationSlug: string | null =
  78. configStore.lastOrganization ?? organizations[0]?.slug ?? null;
  79. const routes = useRoutes();
  80. const params = useParams<{orgId?: string}>();
  81. // XXX(epurkhiser): When running in deploy preview mode customer domains are
  82. // not supported correctly. Do NOT use the customer domain from the params.
  83. const orgSlug = DEPLOY_PREVIEW_CONFIG
  84. ? lastOrganizationSlug
  85. : params.orgId || lastOrganizationSlug;
  86. // Provided to the OrganizationLoaderContext. Loads the organization if it is
  87. // not already present.
  88. const loadOrganization = useCallback(() => {
  89. // Nothing to do if we already have the organization loaded
  90. if (organization && organization.slug === orgSlug) {
  91. return;
  92. }
  93. if (!orgSlug) {
  94. OrganizationStore.setNoOrganization();
  95. return;
  96. }
  97. metric.mark({name: 'organization-details-fetch-start'});
  98. fetchOrganizationDetails(api, orgSlug, false, true);
  99. }, [api, orgSlug, organization]);
  100. // Take a measurement for when organization details are done loading and the
  101. // new state is applied
  102. useEffect(
  103. () => {
  104. if (organization === null) {
  105. return;
  106. }
  107. metric.measure({
  108. name: 'app.component.perf',
  109. start: 'organization-details-fetch-start',
  110. data: {
  111. name: 'org-details',
  112. route: getRouteStringFromRoutes(routes),
  113. organization_id: parseInt(organization.id, 10),
  114. },
  115. });
  116. },
  117. // Ignore the `routes` dependency for the metrics measurement
  118. // eslint-disable-next-line react-hooks/exhaustive-deps
  119. [organization]
  120. );
  121. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  122. // boot. We should fix the types here in the future
  123. const user: User | null = configStore.user;
  124. // It may be possible for the user to use the sudo modal to load the organization.
  125. useEffect(() => {
  126. if (!error) {
  127. // If the user has an active staff session, the response will not return a
  128. // 403 but access scopes will be an empty list.
  129. if (user?.isSuperuser && user?.isStaff && organization?.access?.length === 0) {
  130. openSudo({
  131. isSuperuser: true,
  132. needsReload: true,
  133. closeEvents: 'none',
  134. closeButton: false,
  135. });
  136. }
  137. return;
  138. }
  139. if (user?.isSuperuser && error.status === 403) {
  140. openSudo({
  141. isSuperuser: true,
  142. needsReload: true,
  143. closeEvents: 'none',
  144. closeButton: false,
  145. });
  146. }
  147. // This `catch` can swallow up errors in development (and tests)
  148. // So let's log them. This may create some noise, especially the test case where
  149. // we specifically test this branch
  150. console.error(error); // eslint-disable-line no-console
  151. }, [user, error, organization]);
  152. // Switch organizations when the orgId changes
  153. const lastOrgId = useRef(orgSlug);
  154. useEffect(() => {
  155. if (orgSlug && lastOrgId.current !== orgSlug) {
  156. // Only switch on: org1 -> org2
  157. // Not on: undefined -> org1
  158. // Also avoid: org1 -> undefined -> org1
  159. if (lastOrgId.current) {
  160. switchOrganization();
  161. }
  162. lastOrgId.current = orgSlug;
  163. }
  164. }, [orgSlug]);
  165. return (
  166. <OrganizationLoaderContext.Provider value={loadOrganization}>
  167. <OrganizationContext.Provider value={organization}>
  168. <LegacyOrganizationContextProvider value={organization}>
  169. {children}
  170. </LegacyOrganizationContextProvider>
  171. </OrganizationContext.Provider>
  172. </OrganizationLoaderContext.Provider>
  173. );
  174. }