organizationContext.tsx 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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. return;
  95. }
  96. metric.mark({name: 'organization-details-fetch-start'});
  97. fetchOrganizationDetails(api, orgSlug, false, true);
  98. }, [api, orgSlug, organization]);
  99. // Take a measurement for when organization details are done loading and the
  100. // new state is applied
  101. useEffect(
  102. () => {
  103. if (organization === null) {
  104. return;
  105. }
  106. metric.measure({
  107. name: 'app.component.perf',
  108. start: 'organization-details-fetch-start',
  109. data: {
  110. name: 'org-details',
  111. route: getRouteStringFromRoutes(routes),
  112. organization_id: parseInt(organization.id, 10),
  113. },
  114. });
  115. },
  116. // Ignore the `routes` dependency for the metrics measurement
  117. // eslint-disable-next-line react-hooks/exhaustive-deps
  118. [organization]
  119. );
  120. // XXX(epurkhiser): User may be null in some scenarios at this point in app
  121. // boot. We should fix the types here in the future
  122. const user: User | null = configStore.user;
  123. // If we've had an error it may be possible for the user to use the sudo
  124. // modal to load the organization.
  125. useEffect(() => {
  126. if (!error) {
  127. return;
  128. }
  129. if (user?.isSuperuser && error.status === 403) {
  130. openSudo({isSuperuser: true, needsReload: true});
  131. }
  132. // This `catch` can swallow up errors in development (and tests)
  133. // So let's log them. This may create some noise, especially the test case where
  134. // we specifically test this branch
  135. console.error(error); // eslint-disable-line no-console
  136. }, [user, error]);
  137. // Switch organizations when the orgId changes
  138. const lastOrgId = useRef(orgSlug);
  139. useEffect(() => {
  140. if (orgSlug && lastOrgId.current !== orgSlug) {
  141. // Only switch on: org1 -> org2
  142. // Not on: undefined -> org1
  143. // Also avoid: org1 -> undefined -> org1
  144. if (lastOrgId.current) {
  145. switchOrganization();
  146. }
  147. lastOrgId.current = orgSlug;
  148. }
  149. }, [orgSlug]);
  150. return (
  151. <OrganizationLoaderContext.Provider value={loadOrganization}>
  152. <OrganizationContext.Provider value={organization}>
  153. <LegacyOrganizationContextProvider value={organization}>
  154. {children}
  155. </LegacyOrganizationContextProvider>
  156. </OrganizationContext.Provider>
  157. </OrganizationLoaderContext.Provider>
  158. );
  159. }